<?php
require_once "protected/include/ks3File/Ks3Client.class.php";
require_once "protected/include/ks3File/core/Utils.class.php";
class SystemController extends BaseController {
    /**
     * 获取合集列表数据
     * @param {string} params.claimStatus - 认领状态：1、未认领；2、已被认领
     * @param {string} params.status - 审核状态（待审核/审核通过/审核拒绝/再次审核/全部状态）
     * @param {string} params.sort - 排序方式（默认排序/提交时间 降序/提交时间 升序）
     * @param {string} params.keyword - 合集ID/名称/描述关键词
     * @param {string} params.submitter - 提交者
     * @param {string} params.startDate - 开始日期
     * @param {string} params.endDate - 结束日期
     * @param {number} params.page - 页码
     * @param {number} params.pageSize - 每页条数
     * @returns {Promise<Object>} 包含列表数据和分页信息的对象
     * @throws {Error} 当请求失败时抛出异常
     */
    function actionGetCollectionListForPage() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $claimStatus = (int)arg("claimStatus", 0);
        $status = (int)arg("status", 0);
        $sort = (int)arg("sort", 0);
        $keyword = (string)arg("keyword", "");
        $submitter = (string)arg("submitter", "");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 每页最多允许查询10条
        if ($pagesize > 10) {
            $pagesize = 10;
        }

        // 构建查询条件
        $where = " 1=1 ";
        if ($claimStatus != 0) {
            $where .= " and claimed_status = $claimStatus";
        }
        if ($status != 0) {
            $where .= " and audit_status = $status";
        }
        if ($keyword != "") {
            $where .= " and (collection_id like '%$keyword%' or name like '%$keyword%' or description like '%$keyword%')";
        }
        if ($submitter != "") {
            $where .= " and submit_user_id = '$submitter'";
        }
        if ($startDate != "") {
            $where .= " and submit_time >= '$startDate'";
        }
        if ($endDate != "") {
            $where .= " and submit_time <= '$endDate'";
        }

        // 构建排序条件
        $sortSql = "id desc";
        if ($sort == 1) {
            $sortSql = "submit_time desc";
        }
        if ($sort == 2) {
            $sortSql = "submit_time asc";
        }

        // 计算分页起始位置
        $start = ($pagenum - 1) * $pagesize;

        // 构建查询SQL
        $sql = "select * from au_content_collection where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_content_collection where $where";

        // 执行查询
        $collectionModel = new Collection(); // 假设存在对应的模型类
        $collectionList = $collectionModel->query($sql);
        $Auitor = new Auditor();
        
        // 处理认领人名称
        $newList = [];
        foreach ($collectionList as $item) {
            $user_auditor = $Auitor->find(["id" => $item["claimed_by"]]);
            $item["claimed_by_name"] = $user_auditor ? $user_auditor["real_name"] : "--";
            $newList[] = $item;
        }

        // 获取总数
        $totalData = $collectionModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;

        // 返回结果
        success([
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }
    /**
        * 获取媒体内容列表数据
        * @param {string} params.claimStatus - 认领状态：1、未认领；2、已被认领'
        * @param {string} params.contentType - 内容类型（全部类型/图片/视频/音频/文档）
        * @param {string} params.status - 审核状态（待审核/审核通过/审核拒绝/再次审核/全部状态）
        * @param {string} params.sort - 排序方式（默认排序/提交时间 降序/提交时间 升序/优先级 高到低/优先级 低到高）
        * @param {string} params.keyword - 内容ID/关键词
        * @param {string} params.submitter - 提交者
        * @param {string} params.startDate - 开始日期
        * @param {string} params.endDate - 结束日期
        * @param {string} params.violationType - 疑似违规类型
        * @param {number} params.page - 页码
        * @param {number} params.pageSize - 每页条数
        * @returns {Promise<Object>} 包含列表数据和分页信息的对象
        * @throws {Error} 当请求失败时抛出异常
     */
    function  actionGetMediaListFoPage(){
        // 接收参数
        $pagenum = (int)arg("page",1);
        $pagesize = (int)arg("pageSize",10);
        $contentType = (int)arg("contentType",0);
        $claimStatus = (int)arg("claimStatus",0);
        $status = (int)arg("status",0);
        $sort = (int)arg("sort",0);
        $keyword = (string)arg("keyword","");
        $submitter = (string)arg("submitter","");
        $startDate = (string)arg("startDate","");
        $endDate = (string)arg("endDate","");
        $violationType = (string)arg("violationType","");

        // 每页最多允许查询10条
        if($pagesize/1 >10){
            $pagesize=10;
        }
        // 参数有可能不存在，对入参进行验证，然后构建查询条件
        $where = " 1=1 ";
        if($contentType != 0){
            $where .= " and content_type = $contentType";
        }
        if($claimStatus != 0){
            $where .= " and claimed_status = $claimStatus";
        }
        if($status != 0){
            $where .= " and audit_status = $status";
        }
        if($keyword != ""){
            $where .= " and (content_id like '%$keyword%' or title like '%$keyword%' or content_desc like '%$keyword%')";
        }
        if($submitter != ""){
            $where .= " and submit_user_id = '$submitter'";
        }
        if($startDate != ""){
            $where .= " and submit_time >= '$startDate'";
        }
        if($endDate != ""){
            $where .= " and submit_time <= '$endDate'";
        }
        if($violationType != ""){
            $where .= " and ai_suspect_type = '$violationType'";
        }
        $sortSql = "id desc";
        if($sort/1 == 1){
            $sortSql = "submit_time desc";
        }
        if($sort/1 == 2){
            $sortSql = "submit_time asc";
        }
        if($sort/1 == 3){
            $sortSql = "priority desc";
        }
        if($sort/1 == 4){
            $sortSql = "priority asc";
        }
        $start = ($pagenum-1)*$pagesize;
        $sql = "select * from au_media_content where $where order by $sortSql limit $start , $pagesize";
        $sqlCount = "select count(*) as total from au_media_content where $where";
        
        $mediaContent = new MediaContent();
        $mediaContentList = $mediaContent->query($sql);
        $Auitor = new Auditor();
        $newList = [];
        foreach($mediaContentList as $item){
            $user_auditor = $Auitor->find(["id"=>$item["claimed_by"]]);
            if($user_auditor == false){
                $item["claimed_by_name"] = "--";
            }else{
                $item["claimed_by_name"] = $user_auditor["real_name"];
            }
            $newList[] = $item;
        }
        $total = $mediaContent->query($sqlCount);
        $total = $total[0]["total"];
        success(array(
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ));
    }

    /**
     * 获取媒体内容统计数据
     * 包括：待审核总数及同比、今日已审核及同比、违规总数及同比、平均处理时长及同比
     * @returns {Promise<Object>} 统计数据对象
     */
    function actionGetMediaStats() {
        // 时间范围定义（今日和昨日）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d H:i:s');
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
        
        $mediaContent = new MediaContent();

        // 1. 待审核总数（审核状态为待审核，假设状态值为1）及同比
        list($todayPending, $yesterdayPending) = $this->getCompareData(
            $mediaContent,
            "audit_status = 1",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        // $pendingPercent = $this->calculatePercentage($todayPending, $yesterdayPending);
        $pendingChange = $this->calculateChange($todayPending, $yesterdayPending);

        // 2. 今日已审核总数（审核状态为通过/拒绝/再次审核，假设状态值为2/3/4）及同比
        list($todayAudited, $yesterdayAudited) = $this->getCompareData(
            $mediaContent,
            "audit_status in (2,3,4)",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd,
            "audit_time"  // 已审核以审核时间为准
        );
        $auditedChange = $this->calculateChange($todayAudited, $yesterdayAudited);

        // 3. 违规内容总数（存在疑似违规类型）及同比
        list($todayViolation, $yesterdayViolation) = $this->getCompareData(
            $mediaContent,
            "ai_suspect_type != ''",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $violationChange = $this->calculateChange($todayViolation, $yesterdayViolation);

        // 4. 平均处理时长（分钟）及同比
        list($todayAvgTime, $yesterdayAvgTime) = $this->getAvgHandleTime(
            $mediaContent,
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $avgTimeChange = $this->calculateChange($todayAvgTime, $yesterdayAvgTime);

        success([
            'pending' => [
                'total' => $todayPending,
                'percent' => round($pendingChange['percent'], 2),
                'trend' => $pendingChange['trend']  // 新增：上升1/下降-1/持平0
            ],
            'audited' => [
                'total' => $todayAudited,
                'percent' => round($auditedChange['percent'], 2),
                'trend' => $auditedChange['trend']
            ],
            'violation' => [
                'total' => $todayViolation,
                'percent' => round($violationChange['percent'], 2),
                'trend' => $violationChange['trend']
            ],
            'avgHandleTime' => [
                'minutes' => round($todayAvgTime, 2),
                'percent' => round($avgTimeChange['percent'], 2),
                'trend' => $avgTimeChange['trend']
            ]
        ]);
    }
    /**
     * 通用获取同比数据的方法
     * @param object $model 数据模型
     * @param string $condition 查询条件
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @param string $timeField 时间字段（默认submit_time）
     * @return array [今日数量, 昨日数量]
     */
    private function getCompareData($model, $condition, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd, $timeField = 'submit_time') {
        $todaySql = "select count(*) as num from au_media_content where $condition and $timeField between '$todayStart' and '$todayEnd'";
        $yesterdaySql = "select count(*) as num from au_media_content where $condition and $timeField between '$yesterdayStart' and '$yesterdayEnd'";
        if($todayStart == null || $todayEnd == null || $yesterdayStart == null || $yesterdayEnd == null){
            $todaySql = "select count(*) as num from au_media_content where $condition ";
            $yesterdaySql = "select count(*) as num from au_media_content where $condition";
        
        }
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (int)($todayData[0]['num'] ?? 0),
            (int)($yesterdayData[0]['num'] ?? 0)
        ];
    }

    /**
     * 获取平均处理时长（分钟）
     * @param object $model 数据模型
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @return array [今日平均时长, 昨日平均时长]
     */
    private function getAvgHandleTime($model, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd) {
        // 计算审核时间与提交时间的差值（秒），转换为分钟
        $todaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                     from au_media_content 
                     where audit_status in (2,3,4) and audit_time between '$todayStart' and '$todayEnd'";
                     
        $yesterdaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                         from au_media_content 
                         where audit_status in (2,3,4) and audit_time between '$yesterdayStart' and '$yesterdayEnd'";
                         
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (float)($todayData[0]['avg_time'] ?? 0),
            (float)($yesterdayData[0]['avg_time'] ?? 0)
        ];
    }

    /**
     * 计算同比百分比
     * @param float $current 当前值
     * @param float $previous 往期值
     * @return float 百分比（正数为上升，负数为下降）
     */
    private function calculatePercentage($current, $previous) {
        if ($previous == 0) {
            return $current > 0 ? 100 : 0;  // 往期为0时，当前有值则视为100%增长
        }
        return (($current - $previous) / $previous) * 100;
    }
    /**
     * 计算同比变化（百分比+趋势）
     * @param float $current 当前值
     * @param float $previous 往期值
     * @return array 包含百分比和趋势（上升/下降/持平）的数组
     */
    private function calculateChange($current, $previous) {
        $percent = 0;
        $trend = 0; // 默认持平
        
        if ($previous == 0) {
            if ($current > 0) {
                $percent = 100;
                $trend = 1;
            }
        } else {
            $percent = (($current - $previous) / $previous) * 100;
            if ($percent > 0) {
                $trend = 1;
            } elseif ($percent < 0) {
                $trend = -1;
            }
        }
        
        return [
            'percent' => $percent,
            'trend' => $trend
        ];
    }

    /**
     * 批量认领媒体内容
     * @param {Array} params.ids - 媒体内容业务ID数组（如["MED-202407068", "MED-202407056"]）
     * @returns {Promise<Object>} 包含处理结果的对象
     * @throws {Error} 当请求失败时抛出异常
     */
    function actionBatchClaim() {
        // 获取并解析JSON入参
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 验证入参
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        
        $ids = array_map(function($id) {
            // 过滤非法字符，防止SQL注入
            return trim(addslashes($id));
        }, $params['ids']);
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        // 获取当前登录用户ID（实际应用中需根据权限系统获取）
        $currentUserId = $this->getLoginUserId(); // 假设该方法已实现
        if (empty($currentUserId)) {
            error('请先登录');
        }
        
        $mediaContent = new MediaContent();
        
        // 构建ID字符串
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 检查待认领的内容是否存在且处于未认领状态
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND claimed_status = 1"; // 1表示未认领
        $validIds = $mediaContent->query($checkSql);
        
        if ($validIds == false || count($validIds)<=0) {
            error("没有可以认领的任务");
        }
        
        // 提取有效的content_id
        $validContentIds = array_column($validIds, 'content_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        // 执行批量更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_media_content 
                    SET claimed_status = 2,  -- 2表示已认领
                        claimed_by = $currentUserId,
                        claimed_time = '$now',
                        updated_at = '$now'
                    WHERE content_id IN ($validIdsStr)
                    AND claimed_status = 1"; // 再次确认未认领状态，防止并发问题
        
        $affectedRows = $mediaContent->execute($updateSql);
        
        // 计算失败的ID
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'claimedCount' => $affectedRows,
            'claimedIds' => $validContentIds,
            'failedIds' => $failedIds
        ],'批量认领完成');
    }
    /**
     * 批量审核通过媒体内容
     * @param {Array} params.ids - 媒体内容业务ID数组（如["MED-202407068", "MED-202407056"]）
     * @returns {Promise<Object>} 包含处理结果的对象
     * @throws {Error} 当请求失败时抛出异常
     */
    function actionBatchAuditPass() {
        // 获取并解析JSON入参
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 验证入参
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        
        $ids = array_map(function($id) {
            // 过滤非法字符，防止SQL注入
            return trim(addslashes($id));
        }, $params['ids']);
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        // 获取当前登录用户信息
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';
        
        $mediaContent = new MediaContent();

        // 判断选中的内容是否被当前用户认领，不是被当前用户认领的任务，不能进行审核
        $idsStr = "'" . implode("','", $ids) . "'";
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $mediaContent->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些内容");
        }
        
        // 构建ID字符串
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 检查待审核的内容是否存在且处于可审核状态（待审核/再次审核）
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND audit_status IN (1, 4)"; // 1:待审核 4:再次审核
        $validIds = $mediaContent->query($checkSql);
        
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可审核通过的内容");
        }
        
        // 提取有效的content_id
        $validContentIds = array_column($validIds, 'content_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        // 执行批量更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_media_content 
                    SET audit_status = 2,  -- 2:审核通过
                        auditor_id = $currentUserId,
                        auditor_name = '$auditorName',
                        audit_time = '$now',
                        chk_num = chk_num + 1,  -- 审核次数+1
                        updated_at = '$now'
                    WHERE content_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)"; // 再次确认状态，防止并发问题
        
        $affectedRows = $mediaContent->execute($updateSql);
        
        // 计算失败的ID
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'passedCount' => $affectedRows,
            'passedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量审核通过完成');
    }

    /**
     * 批量拒绝媒体内容
     * @param {Array} params.ids - 媒体内容业务ID数组（如["MED-202407068", "MED-202407056"]）
     * @param {number} params.reason - 拒绝原因（31：拒绝-涉黄/32：拒绝-涉政/33：拒绝-广告/34：拒绝-其他）
     * @returns {Promise<Object>} 包含处理结果的对象
     * @throws {Error} 当请求失败时抛出异常
     */
    function actionBatchAuditReject() {
        // 获取并解析JSON入参
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 验证入参
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        if (!isset($params['rejectType']) || !in_array($params['rejectType'], [31, 32, 33, 34])) {
            error('无效的拒绝原因，必须是31-34之间的整数');
        }
        
        $ids = array_map(function($id) {
            // 过滤非法字符，防止SQL注入
            return trim(addslashes($id));
        }, $params['ids']);
        $rejectReason = (int)$params['rejectType'];
        $remark = (string)$params['remark'];
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        // 获取当前登录用户信息
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';
        
        $mediaContent = new MediaContent();
        
        // 构建ID字符串
        $idsStr = "'" . implode("','", $ids) . "'";
        // 判断选中的内容是否被当前用户认领，不是被当前用户认领的任务，不能进行审核
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $mediaContent->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些内容");
        }
        // 检查待审核的内容是否存在且处于可审核状态（待审核/再次审核）
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND audit_status IN (1, 4)"; // 1:待审核 4:再次审核
        $validIds = $mediaContent->query($checkSql);
        
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可拒绝的内容");
        }
        
        // 提取有效的content_id
        $validContentIds = array_column($validIds, 'content_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        // 执行批量更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_media_content 
                    SET audit_status = $rejectReason,  -- 设置拒绝原因状态
                        auditor_id = $currentUserId,
                        auditor_name = '$auditorName',
                        audit_time = '$now',
                        chk_num = chk_num + 1,  -- 审核次数+1
                        remark = '$remark',
                        updated_at = '$now'
                    WHERE content_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)"; // 再次确认状态，防止并发问题
        
        $affectedRows = $mediaContent->execute($updateSql);
        
        // 计算失败的ID
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'rejectedCount' => $affectedRows,
            'rejectedIds' => $validContentIds,
            'failedIds' => $failedIds,
            'reason' => $rejectReason
        ], '批量拒绝完成');
    }

    /**
     * 批量标记为复查
     */
    function actionBatchMarkReview(){
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        $ids = array_map(function($id) {
            // 过滤非法字符，防止SQL注入
            return trim(addslashes($id));
        }, $params['ids']);
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        $remark = (string)$params['remark'];
        if (empty($remark)) {
            error('remark不能为空');
        }
        $mediaContent = new MediaContent();
        // 获取当前登录用户信息
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        // 构建ID字符串
        $idsStr = "'" . implode("','", $ids) . "'";
        // 判断选中的内容是否被当前用户认领，不是被当前用户认领的任务，不能进行审核
        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $mediaContent->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些内容");
        }

        $checkSql = "SELECT content_id FROM au_media_content 
                    WHERE content_id IN ($idsStr) 
                    AND audit_status not IN (1, 4)";
        $validIds = $mediaContent->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可标记为复查的内容");
        }
        $validContentIds = array_column($validIds, 'content_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_media_content 
                    SET audit_status = 4,  -- 设置为复查状态
                        remark = '$remark',
                        updated_at = '$now'
                    WHERE content_id IN ($validIdsStr)";
        $affectedRows = $mediaContent->execute($updateSql);
        if ($affectedRows <= 0) {
            error("标记为复查失败");
        }
        success([
            'markedCount' => $affectedRows,
            'markedIds' => $validContentIds,
        ], '批量标记为复查完成');

    }

    /**
     * 批量认领合集
     * @param {Array} params.ids - 合集业务ID数组（如["COL-202407068", "COL-202407056"]）
     * @returns {Promise<Object>} 包含处理结果的对象
     */
    function actionBatchClaimCollection() {
        // 获取并解析JSON入参
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 验证入参
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        
        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        // 获取当前登录用户ID
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        
        $collectionModel = new Collection();
        
        // 构建ID字符串
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 检查待认领的合集是否存在且处于未认领状态
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND claimed_status = 1"; // 1表示未认领
        $validIds = $collectionModel->query($checkSql);
        
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可以认领的合集");
        }
        
        // 提取有效的collection_id
        $validContentIds = array_column($validIds, 'collection_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        // 执行批量更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_content_collection 
                    SET claimed_status = 2,  -- 2表示已认领
                        claimed_by = $currentUserId,
                        claimed_time = '$now',
                        updated_at = '$now'
                    WHERE collection_id IN ($validIdsStr)
                    AND claimed_status = 1"; // 防止并发问题
        
        $affectedRows = $collectionModel->execute($updateSql);
        
        // 计算失败的ID
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'claimedCount' => $affectedRows,
            'claimedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量认领完成');
    }

    /**
     * 批量审核通过合集
     * @param {Array} params.ids - 合集业务ID数组
     * @returns {Promise<Object>} 包含处理结果的对象
     */
    function actionBatchAuditPassCollection() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        
        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';
        
        $collectionModel = new Collection();
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 验证权限（必须是当前用户认领的）
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些合集");
        }
        
        // 检查可审核状态（待审核/再次审核）
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND audit_status IN (1, 4)"; // 1:待审核 4:再次审核
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可审核通过的合集");
        }
        
        $validContentIds = array_column($validIds, 'collection_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_content_collection 
                    SET audit_status = 2,  -- 2:审核通过
                        auditor_id = $currentUserId,
                        auditor_name = '$auditorName',
                        audit_time = '$now',
                        chk_num = IFNULL(chk_num, 0) + 1,  -- 审核次数+1
                        updated_at = '$now'
                    WHERE collection_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)";
        
        $affectedRows = $collectionModel->execute($updateSql);
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'passedCount' => $affectedRows,
            'passedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量审核通过完成');
    }

    /**
     * 批量拒绝合集
     * @param {Array} params.ids - 合集业务ID数组
     * @param {number} params.rejectType - 拒绝原因（31：涉黄/32：涉政/33：广告/34：其他）
     * @param {string} params.remark - 拒绝备注
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchAuditRejectCollection() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 入参验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        if (!isset($params['rejectType']) || !in_array($params['rejectType'], [31, 32, 33, 34])) {
            error('无效的拒绝原因，必须是31-34之间的整数');
        }
        
        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        $rejectReason = (int)$params['rejectType'];
        $remark = (string)($params['remark'] ?? '');
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';
        
        $collectionModel = new Collection();
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 权限验证
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些合集");
        }
        
        // 状态验证
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND audit_status IN (1, 4)";
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可拒绝的合集");
        }
        
        $validContentIds = array_column($validIds, 'collection_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_content_collection 
                    SET audit_status = $rejectReason,
                        auditor_id = $currentUserId,
                        auditor_name = '$auditorName',
                        audit_time = '$now',
                        chk_num = IFNULL(chk_num, 0) + 1,
                        remark = '$remark',
                        updated_at = '$now'
                    WHERE collection_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)";
        
        $affectedRows = $collectionModel->execute($updateSql);
        $failedIds = array_diff($ids, $validContentIds);
        
        success([
            'rejectedCount' => $affectedRows,
            'rejectedIds' => $validContentIds,
            'failedIds' => $failedIds,
            'reason' => $rejectReason
        ], '批量拒绝完成');
    }

    /**
     * 批量标记合集为复查
     * @param {Array} params.ids - 合集业务ID数组
     * @param {string} params.remark - 复查备注（必填）
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchMarkReviewCollection() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        $remark = (string)($params['remark'] ?? '');
        if (empty($remark)) {
            error('复查备注不能为空');
        }
        
        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        
        if (empty($ids)) {
            error('ids数组不能为空');
        }
        
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }
        
        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        
        $collectionModel = new Collection();
        $idsStr = "'" . implode("','", $ids) . "'";
        
        // 权限验证
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND claimed_by = $currentUserId";
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限操作这些合集");
        }
        
        // 状态验证（非待审核/再次审核状态才能标记复查）
        $checkSql = "SELECT collection_id FROM au_content_collection 
                    WHERE collection_id IN ($idsStr) 
                    AND audit_status NOT IN (1, 4)";
        $validIds = $collectionModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可标记为复查的合集");
        }
        
        $validContentIds = array_column($validIds, 'collection_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_content_collection 
                    SET audit_status = 4,  -- 4:再次审核（复查）
                        remark = '$remark',
                        updated_at = '$now'
                    WHERE collection_id IN ($validIdsStr)";
        
        $affectedRows = $collectionModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("标记为复查失败");
        }
        
        success([
            'markedCount' => $affectedRows,
            'markedIds' => $validContentIds,
        ], '批量标记为复查完成');
    }

    /**
     * 获取合集统计数据
     * 包括：待审核总数及同比、今日已审核及同比、已拒绝总数及同比、平均处理时长及同比
     * @returns {Promise<Object>} 统计数据对象
     */
    function actionGetCollectionStats() {
        // 时间范围定义（今日和昨日）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d H:i:s');
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
        
        $collectionModel = new Collection();

        // 1. 待审核总数（审核状态为待审核，状态值为1）及同比
        list($todayPending, $yesterdayPending) = $this->getCollectionCompareData(
            $collectionModel,
            "audit_status = 1",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $pendingChange = $this->calculateChange($todayPending, $yesterdayPending);

        // 2. 今日已审核总数（审核状态为通过/拒绝/再次审核，状态值为2/31-34/4）及同比
        list($todayAudited, $yesterdayAudited) = $this->getCollectionCompareData(
            $collectionModel,
            "audit_status in (2,4,31,32,33,34)",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd,
            "audit_time"  // 已审核以审核时间为准
        );
        $auditedChange = $this->calculateChange($todayAudited, $yesterdayAudited);

        // 3. 已拒绝合集总数（审核状态为拒绝，状态值31-34）及同比
        list($todayRejected, $yesterdayRejected) = $this->getCollectionCompareData(
            $collectionModel,
            "audit_status in (31,32,33,34)",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $rejectedChange = $this->calculateChange($todayRejected, $yesterdayRejected);

        // 4. 平均处理时长（分钟）及同比
        list($todayAvgTime, $yesterdayAvgTime) = $this->getCollectionAvgHandleTime(
            $collectionModel,
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $avgTimeChange = $this->calculateChange($todayAvgTime, $yesterdayAvgTime);

        success([
            'pending' => [
                'total' => $todayPending,
                'percent' => round($pendingChange['percent'], 2),
                'trend' => $pendingChange['trend']  // 上升1/下降-1/持平0
            ],
            'audited' => [
                'total' => $todayAudited,
                'percent' => round($auditedChange['percent'], 2),
                'trend' => $auditedChange['trend']
            ],
            'rejected' => [
                'total' => $todayRejected,
                'percent' => round($rejectedChange['percent'], 2),
                'trend' => $rejectedChange['trend']
            ],
            'avgHandleTime' => [
                'minutes' => round($todayAvgTime, 2),
                'percent' => round($avgTimeChange['percent'], 2),
                'trend' => $avgTimeChange['trend']
            ]
        ]);
    }

    /**
     * 合集通用获取同比数据的方法
     * @param object $model 数据模型
     * @param string $condition 查询条件
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @param string $timeField 时间字段（默认submit_time）
     * @return array [今日数量, 昨日数量]
     */
    private function getCollectionCompareData($model, $condition, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd, $timeField = 'submit_time') {
        $todaySql = "select count(*) as num from au_content_collection where $condition and $timeField between '$todayStart' and '$todayEnd'";
        $yesterdaySql = "select count(*) as num from au_content_collection where $condition and $timeField between '$yesterdayStart' and '$yesterdayEnd'";
        
        if(empty($todayStart) || empty($todayEnd) || empty($yesterdayStart) || empty($yesterdayEnd)){
            $todaySql = "select count(*) as num from au_content_collection where $condition";
            $yesterdaySql = "select count(*) as num from au_content_collection where $condition";
        }
        
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (int)($todayData[0]['num'] ?? 0),
            (int)($yesterdayData[0]['num'] ?? 0)
        ];
    }

    /**
     * 获取合集平均处理时长（分钟）
     * @param object $model 数据模型
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @return array [今日平均时长, 昨日平均时长]
     */
    private function getCollectionAvgHandleTime($model, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd) {
        // 计算审核时间与提交时间的差值（秒），转换为分钟
        $todaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                    from au_content_collection 
                    where audit_status in (2,31,32,33,34) and audit_time between '$todayStart' and '$todayEnd'";
                    
        $yesterdaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                        from au_content_collection 
                        where audit_status in (2,31,32,33,34) and audit_time between '$yesterdayStart' and '$yesterdayEnd'";
                        
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (float)($todayData[0]['avg_time'] ?? 0),
            (float)($yesterdayData[0]['avg_time'] ?? 0)
        ];
    }

    /**
     * 获取合集详情
     * @param {string} params.collection_id - 合集ID（必填）
     * @returns {Promise<Object>} 合集详情数据
     */
    function actionGetCollectionDetail() {
        // 获取合集ID参数
        $collectionId = (string)arg("collectionId", "");
        
        // 参数验证
        if (empty($collectionId)) {
            error('合集ID不能为空');
        }
        
        try {
            $collectionModel = new Collection();
            
            // 查询合集基本信息
            $collection = $collectionModel->find([
                "collection_id" => $collectionId
            ]);
            
            if (!$collection) {
                error('合集不存在');
            }
            
            // 查询合集包含的内容项（取前5条，用于列表展示）
            $items = $collectionModel->query("
            select b.content_id as id,b.title,b.content_type as type 
            from au_collection_media_rel a,au_media_content b 
            where a.media_id=b.content_id and a.collection_id=:cid", [':cid' => $collectionId]);
            
            // 获取总内容数
            $itemCount = $collectionModel->query("
                SELECT COUNT(*) as count 
                from au_collection_media_rel a,au_media_content b 
            where a.media_id=b.content_id and a.collection_id=:cid
            ", [':cid' => $collectionId])[0]['count'] ?? 0;
            
            // 处理审核状态文本映射
            $auditStatusMap = [
                1 => '待审核',
                2 => '审核通过',
                4 => '再次审核',
                31 => '涉黄',
                32 => '涉政',
                33 => '广告',
                34 => '其他'
            ];
            $collection['audit_status_text'] = $auditStatusMap[$collection['audit_status']] ?? '未知状态';
            
            // 组装返回数据
            $result = [
                'collection_id' => $collection['collection_id'],
                'name' => $collection['name'],
                'description' => $collection['description'],
                'submit_user_id' => $collection['submit_user_id'],
                'submit_time' => $collection['submit_time'],
                'audit_status' => $collection['audit_status'],
                'audit_status_text' => $collection['audit_status_text'],
                'claimed_by' => $collection['claimed_by'],
                'claimed_name' => $collection['claimed_by_name'] ?? '--',
                'claimed_time' => $collection['claimed_time'],
                'chk_num' => $collection['chk_num'] ?? 0,
                'item_count' => $itemCount,
                'items' => $items
            ];
            
            success($result);
            
        } catch (Exception $e) {
            error('获取合集详情失败：' . $e->getMessage());
        }
    }

    /**
     * 获取言论内容列表数据
     * @param {string} params.claimStatus - 认领状态：1、未认领；2、已被认领
     * @param {string} params.status - 审核状态（1、待审核/2、审核通过/3、审核拒绝/4、再次审核/0、全部）
     * @param {string} params.contentType - 内容类型（1、文本/2、图文混排/3、带链接/0、全部）
     * @param {string} params.relatedType - 关联类型（media/collection/none/空、全部）
     * @param {string} params.hasSensitive - 是否含敏感词（0、否/1、是/空、全部）
     * @param {string} params.isAnonymous - 是否匿名（0、否/1、是/空、全部）
     * @param {string} params.sort - 排序方式（0、默认排序/1、提交时间降序/2、提交时间升序）
     * @param {string} params.keyword - 言论ID/内容关键词
     * @param {string} params.submitter - 提交者ID
     * @param {string} params.startDate - 开始日期
     * @param {string} params.endDate - 结束日期
     * @param {number} params.page - 页码
     * @param {number} params.pageSize - 每页条数
     * @returns {Promise<Object>} 包含列表数据和分页信息的对象
     */
    function actionGetCommentListForPage() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $claimStatus = (int)arg("claimStatus", 0);
        $status = (int)arg("status", 0);
        $contentType = (int)arg("contentType", 0);
        $relatedType = (string)arg("relatedType", "");
        $hasSensitive = (int)arg("hasSensitive", -1);
        $isAnonymous = (int)arg("isAnonymous", -1);
        $sort = (int)arg("sort", 0);
        $keyword = (string)arg("keyword", "");
        $submitter = (string)arg("submitter", "");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");

        // 限制每页最大条数
        if ($pagesize > 10) {
            $pagesize = 10;
        }

        // 构建查询条件
        $where = " is_deleted = 0 "; // 排除已删除数据

        // 认领状态（1:未认领-claimed_by为空；2:已认领-claimed_by不为空）
        if ($claimStatus != 0) {
            $where .= " and claimed_status = $claimStatus";
        }

        // 审核状态
        if ($status != 0) {
            $where .= " and audit_status = $status";
        }

        // 内容类型
        if ($contentType != 0) {
            $where .= " and content_type = $contentType";
        }

        // 关联类型
        if ($relatedType !== "") {
            $where .= " and related_type = '$relatedType'";
        }

        // 是否含敏感词
        if ($hasSensitive != -1) {
            $where .= " and has_sensitive = $hasSensitive";
        }

        // 是否匿名
        if ($isAnonymous != -1) {
            $where .= " and is_anonymous = $isAnonymous";
        }

        // 关键词搜索（言论ID/内容）
        if ($keyword != "") {
            $where .= " and (comment_id like '%$keyword%' or content like '%$keyword%')";
        }

        // 提交者
        if ($submitter != "") {
            $where .= " and submit_user_id = '$submitter'";
        }

        // 时间范围
        if ($startDate != "") {
            $where .= " and submit_time >= '$startDate'";
        }
        if ($endDate != "") {
            $where .= " and submit_time <= '$endDate'";
        }

        // 排序条件
        $sortSql = "id desc";
        if ($sort == 1) {
            $sortSql = "submit_time desc";
        } elseif ($sort == 2) {
            $sortSql = "submit_time asc";
        }

        // 分页处理
        $start = ($pagenum - 1) * $pagesize;
        $sql = "select * from au_comment_content where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_comment_content where $where";

        // 执行查询
        $commentModel = new Comment(); // 假设存在对应模型
        $commentList = $commentModel->query($sql);
        $Auitor = new Auditor();

        // 处理认领人名称
        $newList = [];
        foreach ($commentList as $item) {
            $user_auditor = $item["claimed_by"] ? $Auitor->find(["id" => $item["claimed_by"]]) : null;
            $item["claimed_by_name"] = $user_auditor ? $user_auditor["real_name"] : "--";
            $newList[] = $item;
        }

        // 获取总数
        $totalData = $commentModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;

        success([
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }

    /**
     * 批量认领言论内容
     * @param {Array} params.ids - 言论业务ID数组（如["COM-5678", "COM-1234"]）
     * @returns {Promise<Object>} 包含处理结果的对象
     */
    function actionBatchClaimComment() {
        // 获取并解析入参
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证参数
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 获取当前登录用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $commentModel = new Comment();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 检查可认领的言论（未删除、未认领）
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_status=1";
        $validIds = $commentModel->query($checkSql);

        if ($validIds === false || count($validIds) <= 0) {
            error("没有可认领的言论");
        }

        // 提取有效ID
        $validContentIds = array_column($validIds, 'comment_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";

        // 执行认领更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_comment_content 
                    SET claimed_status = 2,
                        claimed_by = $currentUserId,
                        claimed_time = '$now',
                        updated_at = '$now'
                    WHERE comment_id IN ($validIdsStr)";
        $affectedRows = $commentModel->execute($updateSql);

        // 计算失败ID
        $failedIds = array_diff($ids, $validContentIds);

        success([
            'claimedCount' => $affectedRows,
            'claimedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量认领完成');
    }

    /**
     * 批量审核通过言论内容
     * @param {Array} params.ids - 言论业务ID数组
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchAuditPassComment() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证参数
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 获取当前用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';

        $commentModel = new Comment();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 验证权限（必须是当前用户认领）
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_by = $currentUserId";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些言论");
        }

        // 验证可审核状态（待审核/再次审核）
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND audit_status IN (1, 4)";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可审核通过的言论");
        }

        $validContentIds = array_column($validIds, 'comment_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";

        // 执行更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_comment_content 
                    SET audit_status = 2,
                        auditor_id = $currentUserId,
                        audit_time = '$now',
                        chk_num = IFNULL(chk_num, 0) + 1,
                        updated_at = '$now'
                    WHERE comment_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)";

        $affectedRows = $commentModel->execute($updateSql);
        $failedIds = array_diff($ids, $validContentIds);

        success([
            'passedCount' => $affectedRows,
            'passedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量审核通过完成');
    }

    /**
     * 批量拒绝言论内容
     * @param {Array} params.ids - 言论业务ID数组
     * @param {number} params.rejectType - 拒绝类型（31:涉黄/32:涉政/33:广告/34:辱骂/35:其他）
     * @param {string} params.rejectReason - 拒绝原因详情
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchAuditRejectComment() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证参数
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        if (!isset($params['rejectType']) || !in_array($params['rejectType'], [31, 32, 33, 34, 35])) {
            error('无效的拒绝类型，必须是31-35之间的整数');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        $rejectType = (int)$params['rejectType'];
        $rejectReason = (string)($params['rejectReason'] ?? '');

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 获取当前用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }
        $auditorName = $currentUser['real_name'] ?? '';

        $commentModel = new Comment();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_by = $currentUserId";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限审核这些言论");
        }

        // 状态验证（待审核/再次审核）
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND audit_status IN (1, 4)";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可拒绝的言论");
        }

        $validContentIds = array_column($validIds, 'comment_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";

        // 执行更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_comment_content 
                    SET audit_status = 3,
                        reject_type = $rejectType,
                        reject_reason = '$rejectReason',
                        auditor_id = $currentUserId,
                        audit_time = '$now',
                        chk_num = IFNULL(chk_num, 0) + 1,
                        updated_at = '$now'
                    WHERE comment_id IN ($validIdsStr)
                    AND audit_status IN (1, 4)";

        $affectedRows = $commentModel->execute($updateSql);
        $failedIds = array_diff($ids, $validContentIds);

        success([
            'rejectedCount' => $affectedRows,
            'rejectedIds' => $validContentIds,
            'failedIds' => $failedIds,
            'rejectType' => $rejectType
        ], '批量拒绝完成');
    }
    /**
     * 获取评论详情
     * @param {string} params.commentId - 评论ID（如COM-040）
     * @returns {Promise<Object>} 包含评论详情的对象
     * @throws {Error} 当请求失败时抛出异常
     */
    function actionGetCommentDetail() {
        // 接收评论ID参数
        $commentId = trim(arg("commentId", ""));
        
        // 验证参数
        if (empty($commentId)) {
            error('评论ID不能为空');
        }
        
        // 防止SQL注入（过滤非法字符）
        $commentId = addslashes($commentId);
        
        // 假设存在评论模型类Comment
        $commentModel = new Comment();
        
        // 构建查询SQL
        $sql = "SELECT * FROM au_comment_content WHERE comment_id = '$commentId' LIMIT 1";
        $commentDetail = $commentModel->query($sql);
        
        // 检查评论是否存在
        if (empty($commentDetail)) {
            error('评论不存在或已被删除');
        }
        $comment = $commentDetail[0];
        
        // 处理关联数据（如评论者信息）
        $Auitor = new Auditor();
        
        // 处理审核者信息（如果有）
        if (!empty($comment["auditor_id"])) {
            $auditorInfo = $Auitor->find(["id" => $comment["auditor_id"]]);
            $comment["auditor_name"] = $auditorInfo ? $auditorInfo["real_name"] : "--";
        } else {
            $comment["auditor_name"] = "--";
        }
        
        // 返回评论详情
        success($comment);
    }
    /**
     * 批量标记言论为复查
     * @param {Array} params.ids - 言论业务ID数组
     * @param {string} params.remark - 复查备注
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchMarkReviewComment() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证参数
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        $remark = (string)($params['remark'] ?? '');
        if (empty($remark)) {
            error('复查备注不能为空');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 获取当前用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $commentModel = new Comment();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_by = $currentUserId";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限操作这些言论");
        }

        // 验证状态（非待审核/非再次审核）
        $checkSql = "SELECT comment_id FROM au_comment_content 
                    WHERE comment_id IN ($idsStr) 
                    AND audit_status NOT IN (1, 4)";
        $validIds = $commentModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可标记为复查的言论");
        }

        $validContentIds = array_column($validIds, 'comment_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";

        // 执行更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_comment_content 
                    SET audit_status = 4,
                        reject_reason = CONCAT(IFNULL(reject_reason, ''), '[复查备注：$remark]'),
                        updated_at = '$now'
                    WHERE comment_id IN ($validIdsStr)";

        $affectedRows = $commentModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("标记复查失败");
        }

        success([
            'markedCount' => $affectedRows,
            'markedIds' => $validContentIds
        ], '批量标记复查完成');
    }
    /**
     * 获取言论内容统计数据
     * 包括：待审核总数及同比、今日已审核及同比、违规总数及同比、平均处理时长及同比
     * @returns {Promise<Object>} 统计数据对象
     */
    function actionGetCommentStats() {
        // 时间范围定义（今日和昨日）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d H:i:s');
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
        
        $commentModel = new Comment(); // 假设存在对应的模型类

        // 1. 待审核总数（审核状态为待审核，状态值为1）及同比
        list($todayPending, $yesterdayPending) = $this->getCommentCompareData(
            $commentModel,
            "audit_status = 1 AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $pendingChange = $this->calculateChange($todayPending, $yesterdayPending);

        // 2. 今日已审核总数（审核状态为通过/拒绝/再次审核，状态值为2/3/4）及同比
        list($todayAudited, $yesterdayAudited) = $this->getCommentCompareData(
            $commentModel,
            "audit_status IN (2,3,4) AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd,
            "audit_time"  // 已审核以审核时间为准
        );
        $auditedChange = $this->calculateChange($todayAudited, $yesterdayAudited);

        // 3. 违规内容总数（含敏感词或审核拒绝）及同比
        list($todayViolation, $yesterdayViolation) = $this->getCommentCompareData(
            $commentModel,
            "(has_sensitive = 1 OR audit_status = 3) AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $violationChange = $this->calculateChange($todayViolation, $yesterdayViolation);

        // 4. 平均处理时长（分钟）及同比
        list($todayAvgTime, $yesterdayAvgTime) = $this->getCommentAvgHandleTime(
            $commentModel,
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $avgTimeChange = $this->calculateChange($todayAvgTime, $yesterdayAvgTime);

        success([
            'pending' => [
                'total' => $todayPending,
                'percent' => round($pendingChange['percent'], 2),
                'trend' => $pendingChange['trend']  // 上升1/下降-1/持平0
            ],
            'audited' => [
                'total' => $todayAudited,
                'percent' => round($auditedChange['percent'], 2),
                'trend' => $auditedChange['trend']
            ],
            'violation' => [
                'total' => $todayViolation,
                'percent' => round($violationChange['percent'], 2),
                'trend' => $violationChange['trend']
            ],
            'avgHandleTime' => [
                'minutes' => round($todayAvgTime, 2),
                'percent' => round($avgTimeChange['percent'], 2),
                'trend' => $avgTimeChange['trend']
            ]
        ]);
    }

    /**
     * 言论统计专用 - 通用获取同比数据的方法
     * @param object $model 数据模型
     * @param string $condition 查询条件
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @param string $timeField 时间字段（默认submit_time）
     * @return array [今日数量, 昨日数量]
     */
    private function getCommentCompareData($model, $condition, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd, $timeField = 'submit_time') {
        $todaySql = "select count(*) as num from au_comment_content where $condition and $timeField between '$todayStart' and '$todayEnd'";
        $yesterdaySql = "select count(*) as num from au_comment_content where $condition and $timeField between '$yesterdayStart' and '$yesterdayEnd'";
        
        // 处理时间参数为空的情况
        if(empty($todayStart) || empty($todayEnd) || empty($yesterdayStart) || empty($yesterdayEnd)){
            $todaySql = "select count(*) as num from au_comment_content where $condition";
            $yesterdaySql = "select count(*) as num from au_comment_content where $condition";
        }

        
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (int)($todayData[0]['num'] ?? 0),
            (int)($yesterdayData[0]['num'] ?? 0)
        ];
    }

    /**
     * 言论统计专用 - 获取平均处理时长（分钟）
     * @param object $model 数据模型
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @return array [今日平均时长, 昨日平均时长]
     */
    private function getCommentAvgHandleTime($model, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd) {
        // 计算审核时间与提交时间的差值（秒），转换为分钟
        $todaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                    from au_comment_content 
                    where audit_status IN (2,3,4) AND is_deleted = 0 and audit_time between '$todayStart' and '$todayEnd'";
                    
        $yesterdaySql = "select avg(TIMESTAMPDIFF(SECOND, submit_time, audit_time)/60) as avg_time 
                        from au_comment_content 
                        where audit_status IN (2,3,4) AND is_deleted = 0 and audit_time between '$yesterdayStart' and '$yesterdayEnd'";
                        
        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (float)($todayData[0]['avg_time'] ?? 0),
            (float)($yesterdayData[0]['avg_time'] ?? 0)
        ];
    }
    /**
     * 获取认证申请列表数据
     * @param {number} params.page - 页码
     * @param {number} params.pageSize - 每页条数
     * @param {number} params.certType - 认证类型（1-个人；2-企业；3-媒体等，0-全部）
     * @param {number} params.auditStatus - 审核状态（1-待审核；2-通过；3-拒绝；4-撤回，0-全部）
     * @param {number} params.claimStatus - 认领状态（1-未认领；2-已认领，0-全部）
     * @param {string} params.keyword - 关键词（申请ID/姓名/公司名称）
     * @param {string} params.startDate - 申请开始时间
     * @param {string} params.endDate - 申请结束时间
     * @param {number} params.sort - 排序（0-默认；1-申请时间降序；2-申请时间升序）
     * @returns {Promise<Object>} 列表及分页信息
     */
    function actionGetCertApplyList() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $certType = (int)arg("certType", 0);
        $auditStatus = (int)arg("auditStatus", 0);
        $claimStatus = (int)arg("claimStatus", 0);
        $keyword = (string)arg("keyword", "");
        $startDate = (string)arg("startDate", "");
        $endDate = (string)arg("endDate", "");
        $sort = (int)arg("sort", 0);

        // 限制每页最大条数
        if ($pagesize > 10) {
            $pagesize = 10;
        }

        // 构建查询条件
        $where = " is_deleted = 0 ";
        if ($certType != 0) {
            $where .= " and cert_type = $certType";
        }
        if ($auditStatus != 0) {
            $where .= " and audit_status = $auditStatus";
        }
        if ($claimStatus != 0) {
            // 1-未认领（claimed_by为空）；2-已认领（claimed_by非空）
            $where .= $claimStatus == 1 ? " and claimed_by is null" : " and claimed_by is not null";
        }
        if ($keyword != "") {
            $keyword = addslashes($keyword);
            $where .= " and (apply_id like '%$keyword%' or realname like '%$keyword%' or company_name like '%$keyword%')";
        }
        if ($startDate != "") {
            $where .= " and apply_time >= '$startDate'";
        }
        if ($endDate != "") {
            $where .= " and apply_time <= '$endDate'";
        }

        // 排序条件
        $sortSql = "id desc";
        if ($sort == 1) {
            $sortSql = "apply_time desc";
        } elseif ($sort == 2) {
            $sortSql = "apply_time asc";
        }

        // 分页处理
        $start = ($pagenum - 1) * $pagesize;
        $sql = "select * from au_certification_apply where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_certification_apply where $where";

        // 执行查询
        $certModel = new Certification(); // 假设存在对应模型
        $list = $certModel->query($sql);
        $Auitor = new Auditor();

        // 补充认领人名称
        $newList = [];
        foreach ($list as $item) {
            $item["claimed_by_name"] = "--";
            if (!empty($item["claimed_by"])) {
                $auditor = $Auitor->find(["id" => $item["claimed_by"]]);
                $item["claimed_by_name"] = $auditor ? $auditor["real_name"] : "--";
            }
            $newList[] = $item;
        }

        // 总数计算
        $totalData = $certModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;

        success([
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }

    /**
     * 批量认领认证申请
     * @param {Array} params.ids - 申请业务ID数组（如["CER-9012", "CER-9013"]）
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchClaimCert() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 入参验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 当前用户验证
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $certModel = new Certification();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 检查可认领的申请（未认领且待审核）
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_by IS NULL";
        $validIds = $certModel->query($checkSql);

        if ($validIds === false || count($validIds) <= 0) {
            error("没有可认领的认证申请");
        }

        $validApplyIds = array_column($validIds, 'apply_id');
        $validIdsStr = "'" . implode("','", $validApplyIds) . "'";

        // 执行认领更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_certification_apply 
                    SET claimed_by = $currentUserId,
                        claimed_time = '$now',
                        claimed_status = 2,
                        updater = '$currentUserId',
                        updated_at = '$now'
                    WHERE apply_id IN ($validIdsStr)
                    AND claimed_by IS NULL";

        $affectedRows = $certModel->execute($updateSql);
        $failedIds = array_diff($ids, $validApplyIds);

        success([
            'claimedCount' => $affectedRows,
            'claimedIds' => $validApplyIds,
            'failedIds' => $failedIds
        ], '批量认领完成');
    }

    /**
     * 批量标记认证为复查
     * @param {Array} params.ids - 申请业务ID数组
     * @param {string} params.remark - 复查备注
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchReviewCert() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证参数
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        $remark = (string)($params['reviewRemark'] ?? '');
        if (empty($remark)) {
            error('复查备注不能为空');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 获取当前用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $certModel = new Certification();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr) 
                    AND is_deleted = 0 
                    AND claimed_by = $currentUserId";
        $validIds = $certModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限操作这些申请");
        }

        // 验证状态（非待审核/非再次审核）
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr)";
        $validIds = $certModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可标记为复查的申请");
        }

        $validContentIds = array_column($validIds, 'apply_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";

        // 执行更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_certification_apply 
                    SET audit_status = 4,
                        reject_reason = CONCAT(IFNULL(reject_reason, ''), '[复查备注：$remark]'),
                        updated_at = '$now'
                    WHERE apply_id IN ($validIdsStr)";

        $affectedRows = $certModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("标记复查失败");
        }

        success([
            'markedCount' => $affectedRows,
            'markedIds' => $validContentIds
        ], '批量标记复查完成');
    }

    /**
     * 批量审核（重新审核）
     */
    function actionAuditCert(){
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 入参验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 当前用户验证
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }

        $certModel = new Certification();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证（必须是当前用户认领的）
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr) 
                    AND claimed_by = $currentUserId 
                    AND audit_status in (2,3,4)";
        $validIds = $certModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可审核通过的认证申请（需先认领且状态为审核通过/拒绝）");
        }

        

        // 执行审核通过更新
        $now = date('Y-m-d H:i:s');
        $audit_status = $params['auditStatus'];
        $updateSql = "UPDATE au_certification_apply 
                    SET audit_status = $audit_status,
                        checked_by = $currentUserId,
                        checked_time = '$now',
                        chk_num = chk_num + 1,
                        updater = '$currentUserId',
                        updated_at = '$now'
                    WHERE apply_id IN ($idsStr)";
        $affectedRows = $certModel->execute($updateSql);

        success([], '批量审核完成');

    }
    /**
     * 获取认证申请详情
     */
    function actionGetCertDetail(){
        $applyId = (string)arg("applyId","");

        if (empty($applyId)) {
            error('申请ID不能为空');
        }

        $certModel = new Certification();

        $certDetail = $certModel->find(["apply_id" => $applyId]);
        if (!$certDetail) {
            error('认证申请不存在');
        }

        success($certDetail, '获取认证申请详情成功');
    }

    /**
     * 批量审核通过认证申请
     * @param {Array} params.ids - 申请业务ID数组
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchAuditPassCert() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 入参验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 当前用户验证
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }

        $certModel = new Certification();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证（必须是当前用户认领的）
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr) 
                    AND claimed_by = $currentUserId 
                    AND audit_status in (1,2,3,4)";
        $validIds = $certModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可审核通过的认证申请（需先认领且状态为待审核）");
        }

        $validApplyIds = array_column($validIds, 'apply_id');
        $validIdsStr = "'" . implode("','", $validApplyIds) . "'";

        // 执行审核通过更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_certification_apply 
                    SET audit_status = 2,
                        checked_by = $currentUserId,
                        checked_time = '$now',
                        chk_num = chk_num + 1,
                        updater = '$currentUserId',
                        updated_at = '$now'
                    WHERE apply_id IN ($validIdsStr)";

        $affectedRows = $certModel->execute($updateSql);
        $failedIds = array_diff($ids, $validApplyIds);

        success([
            'passedCount' => $affectedRows,
            'passedIds' => $validApplyIds,
            'failedIds' => $failedIds
        ], '批量审核通过完成');
    }

    /**
     * 批量拒绝认证申请
     * @param {Array} params.ids - 申请业务ID数组
     * @param {string} params.failReason - 拒绝原因
     * @returns {Promise<Object>} 处理结果
     */
    function actionBatchAuditRejectCert() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 入参验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        if (empty($params['rejectReason'])) {
            error('拒绝原因不能为空');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        $failReason = addslashes((string)$params['rejectReason']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 当前用户验证
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $certModel = new Certification();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 权限验证
        $checkSql = "SELECT apply_id FROM au_certification_apply 
                    WHERE apply_id IN ($idsStr) 
                    AND claimed_by = $currentUserId 
                    AND audit_status in (1,2,3,4)";
        $validIds = $certModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可拒绝的认证申请（需先认领且状态为待审核）");
        }

        $validApplyIds = array_column($validIds, 'apply_id');
        $validIdsStr = "'" . implode("','", $validApplyIds) . "'";

        // 执行拒绝更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_certification_apply 
                    SET audit_status = 3,
                        checked_by = $currentUserId,
                        checked_time = '$now',
                        chk_num = chk_num + 1,
                        fail_reason = '$failReason',
                        updater = '$currentUserId',
                        updated_at = '$now'
                    WHERE apply_id IN ($validIdsStr)";

        $affectedRows = $certModel->execute($updateSql);
        $failedIds = array_diff($ids, $validApplyIds);

        success([
            'rejectedCount' => $affectedRows,
            'rejectedIds' => $validApplyIds,
            'failedIds' => $failedIds,
            'reason' => $params['rejectReason']
        ], '批量拒绝完成');
    }

    
    /**
     * 获取认证申请统计数据
     * 包括：待审核总数及同比、个人/企业/媒体机构认证待审核数及同比、今日已处理数及同比
     * @returns {Promise<Object>} 统计数据对象
     */
    function actionGetCertificationStats() {
        // 时间范围定义（今日和昨日）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d H:i:s');
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));
        
        $certModel = new Certification(); // 假设存在对应的模型类

        // 1. 待审核总数（审核状态为待审核，状态值为1）及同比
        list($todayPendingTotal, $yesterdayPendingTotal) = $this->getCertCompareData(
            $certModel,
            "audit_status = 1 AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $pendingTotalChange = $this->calculateChange($todayPendingTotal, $yesterdayPendingTotal);

        // 2. 个人认证待审核数（认证类型1 + 待审核）及同比
        list($todayPersonal, $yesterdayPersonal) = $this->getCertCompareData(
            $certModel,
            "audit_status = 1 AND cert_type = 1 AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $personalChange = $this->calculateChange($todayPersonal, $yesterdayPersonal);

        // 3. 企业认证待审核数（认证类型2 + 待审核）及同比
        list($todayEnterprise, $yesterdayEnterprise) = $this->getCertCompareData(
            $certModel,
            "audit_status = 1 AND cert_type = 2 AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $enterpriseChange = $this->calculateChange($todayEnterprise, $yesterdayEnterprise);

        // 4. 媒体/机构认证待审核数（认证类型3/4/5 + 待审核）及同比
        list($todayMedia, $yesterdayMedia) = $this->getCertCompareData(
            $certModel,
            "audit_status = 1 AND cert_type IN (3,4,5) AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd
        );
        $mediaChange = $this->calculateChange($todayMedia, $yesterdayMedia);

        // 5. 今日已处理数（审核状态为通过/拒绝，状态值2/3 + 今日审核完成）及同比
        list($todayProcessed, $yesterdayProcessed) = $this->getCertCompareData(
            $certModel,
            "audit_status IN (2,3) AND is_deleted = 0",
            $todayStart, $todayEnd,
            $yesterdayStart, $yesterdayEnd,
            'checked_time' // 已处理以审核完成时间为准
        );
        $processedChange = $this->calculateChange($todayProcessed, $yesterdayProcessed);

        success([
            'pendingTotal' => [
                'total' => $todayPendingTotal,
                'percent' => round($pendingTotalChange['percent'], 2),
                'trend' => $pendingTotalChange['trend']
            ],
            'personalCert' => [
                'total' => $todayPersonal,
                'percent' => round($personalChange['percent'], 2),
                'trend' => $personalChange['trend']
            ],
            'enterpriseCert' => [
                'total' => $todayEnterprise,
                'percent' => round($enterpriseChange['percent'], 2),
                'trend' => $enterpriseChange['trend']
            ],
            'mediaOrgCert' => [
                'total' => $todayMedia,
                'percent' => round($mediaChange['percent'], 2),
                'trend' => $mediaChange['trend']
            ],
            'todayProcessed' => [
                'total' => $todayProcessed,
                'percent' => round($processedChange['percent'], 2),
                'trend' => $processedChange['trend']
            ]
        ]);
    }

    /**
     * 认证申请通用同比数据查询方法
     * @param object $model 数据模型
     * @param string $condition 查询条件
     * @param string $todayStart 今日开始时间
     * @param string $todayEnd 今日结束时间
     * @param string $yesterdayStart 昨日开始时间
     * @param string $yesterdayEnd 昨日结束时间
     * @param string $timeField 时间字段（默认apply_time）
     * @return array [今日数量, 昨日数量]
     */
    private function getCertCompareData($model, $condition, $todayStart, $todayEnd, $yesterdayStart, $yesterdayEnd, $timeField = 'apply_time') {
        $todaySql = "select count(*) as num from au_certification_apply where $condition and $timeField between '$todayStart' and '$todayEnd'";
        $yesterdaySql = "select count(*) as num from au_certification_apply where $condition and $timeField between '$yesterdayStart' and '$yesterdayEnd'";

        // 处理时间参数为空的情况
        if(empty($todayStart) || empty($todayEnd) || empty($yesterdayStart) || empty($yesterdayEnd)){
            $todaySql = "select count(*) as num from au_certification_apply where $condition";
            $yesterdaySql = "select count(*) as num from au_certification_apply where $condition";
        }

        $todayData = $model->query($todaySql);
        $yesterdayData = $model->query($yesterdaySql);
        
        return [
            (int)($todayData[0]['num'] ?? 0),
            (int)($yesterdayData[0]['num'] ?? 0)
        ];
    }

    /**
     * 获取举报统计数据（概览部分）
     * @return void
     */
    function actionGetReportStats() {
        $reportModel = new ReportTo(); // 假设存在Report模型类

        // 时间范围定义（今日和昨日）
        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd = date('Y-m-d H:i:s');
        $yesterdayStart = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $yesterdayEnd = date('Y-m-d 23:59:59', strtotime('-1 day'));

        // 1. 待处理举报（handle_status=1）
        $todayPending = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '1' AND report_time BETWEEN '$todayStart' AND '$todayEnd'")[0]['total'] ?? 0;
        $yesterdayPending = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '1' AND report_time BETWEEN '$yesterdayStart' AND '$yesterdayEnd'")[0]['total'] ?? 0;

        // 2. 已处理举报（handle_status=2）
        $todayProcessed = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '2' AND report_time BETWEEN '$todayStart' AND '$todayEnd'")[0]['total'] ?? 0;
        $yesterdayProcessed = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '2' AND report_time BETWEEN '$yesterdayStart' AND '$yesterdayEnd'")[0]['total'] ?? 0;

        // 3. 已驳回举报（handle_status=3）
        $todayRejected = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '3' AND report_time BETWEEN '$todayStart' AND '$todayEnd'")[0]['total'] ?? 0;
        $yesterdayRejected = $reportModel->query("SELECT count(*) as total FROM au_report_info WHERE handle_status = '3' AND report_time BETWEEN '$yesterdayStart' AND '$yesterdayEnd'")[0]['total'] ?? 0;

        // 计算同比增长率（避免除零错误）
        $getGrowthRate = function($current, $previous) {
            if ($previous == 0) return $current > 0 ? 100 : 0;
            return round(($current - $previous) / $previous * 100, 1);
        };

        success([
            'pending' => [
                'count' => $todayPending,
                'growthRate' => $getGrowthRate($todayPending, $yesterdayPending)
            ],
            'processed' => [
                'count' => $todayProcessed,
                'growthRate' => $getGrowthRate($todayProcessed, $yesterdayProcessed)
            ],
            'rejected' => [
                'count' => $todayRejected,
                'growthRate' => $getGrowthRate($todayRejected, $yesterdayRejected)
            ]
        ]);
    }

    /**
     * 获取举报列表（带筛选和分页）
     * @return void
     */
    function actionGetReportList() {
        $pagenum = (int)arg("page",1);
        $pagesize = (int)arg("pagesize",10);
        $handleStatus = arg("reportStatus");
        $reportType = arg("reportType");
        $keyword = arg("keyword");
        $reporterId = arg("submitter");
        $startDate = arg("start_date");
        $endDate = arg("end_date");
        $sort = (int)arg("sort",0);

        // 构建查询条件
        $where = "1=1";
        if (!empty($handleStatus)) {
            $where .= " AND handle_status = '$handleStatus'";
        }
        if (!empty($reportType)) {
            $where .= " AND reported_type = '$reportType'";
        }
        if (!empty($keyword)) {
            $where .= " AND (report_id LIKE '%$keyword%' OR reported_id LIKE '%$keyword%')";
        }
        if (!empty($reporterId)) {
            $where .= " AND report_user_id = '$reporterId'";
        }
        if (!empty($startDate)) {
            $where .= " AND report_time >= '$startDate 00:00:00'";
        }
        if (!empty($endDate)) {
            $where .= " AND report_time <= '$endDate 23:59:59'";
        }

        // 排序条件
        $sortSql = "id DESC"; // 默认排序
        switch ($sort) {
            case 1:
                $sortSql = "report_time DESC"; // 举报时间降序
                break;
            case 2:
                $sortSql = "report_time ASC"; // 举报时间升序
                break;
            case 3:
                $sortSql = "handle_status ASC, report_time DESC"; // 待处理优先
                break;
        }

        // 分页处理
        $start = ($pagenum - 1) * $pagesize;
        $reportModel = new ReportTo();
        $sql = "SELECT * FROM au_report_info WHERE $where ORDER BY $sortSql LIMIT $start, $pagesize";
        $sqlCount = "SELECT count(*) as total FROM au_report_info WHERE $where";

        $reportList = $reportModel->query($sql);
        $totalData = $reportModel->query($sqlCount);
        $total = $totalData[0]['total'] ?? 0;

        // 处理认领人名称
        $Auitor = new Auditor();
        $newList = [];
        foreach ($reportList as $item) {
            $claimer = $item['claimed_by'] ? $Auitor->find(["id" => $item['claimed_by']]) : null;
            $item['claimed_by_name'] = $claimer ? $claimer['real_name'] : '--';
            $newList[] = $item;
        }

        success([
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }

    /**
     * 批量认领举报
     * @return void
     */
    function actionBatchClaimReport() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 参数验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 验证登录
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        $Auitor = new Auditor();
        $currentUser = $Auitor->find(["id" => $currentUserId]);
        if (!$currentUser) {
            error('审核员信息不存在');
        }

        $reportModel = new ReportTo();
        $idsStr = "'" . implode("','", $ids) . "'";

        // 检查可认领的举报（待处理且未被认领）
        $checkSql = "SELECT report_id FROM au_report_info 
                    WHERE report_id IN ($idsStr) 
                    AND handle_status in (1,4)
                    AND claimed_by IS NULL";
        $validIds = $reportModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("没有可认领的举报");
        }

        $validContentIds = array_column($validIds, 'report_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        $now = date('Y-m-d H:i:s');

        // 执行认领
        $updateSql = "UPDATE au_report_info 
                    SET claimed_by = $currentUserId,
                        claimed_time = '$now',
                        updated_at = '$now'
                    WHERE report_id IN ($validIdsStr)";

        $affectedRows = $reportModel->execute($updateSql);
        $failedIds = array_diff($ids, $validContentIds);

        success([
            'claimedCount' => $affectedRows,
            'claimedIds' => $validContentIds,
            'failedIds' => $failedIds
        ], '批量认领完成');
    }

    /**
     * 批量处理举报（确认有效）
     * @return void
     */
    function actionBatchProcessReport() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        $violationType = trim(addslashes($params['violationType']));
        $processType = trim(addslashes($params['processType']));
        // 参数验证
        if (empty($params['ids']) || !is_array($params['ids'])) {
            error('无效的参数，ids必须为非空数组');
        }
        if (empty($params['violationType']) && $processType != "reject") {

            error('请选择违规类型');
        }
        $remark = (string)($params['remark'] ?? '');

        $ids = array_map(function($id) {
            return trim(addslashes($id));
        }, $params['ids']);
        

        if (empty($ids)) {
            error('ids数组不能为空');
        }

        // 验证登录
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error('请先登录');
        }

        // 权限验证（必须是认领人）
        $reportModel = new ReportTo();
        $idsStr = "'" . implode("','", $ids) . "'";
        $checkSql = "SELECT report_id FROM au_report_info 
                    WHERE report_id IN ($idsStr) 
                    AND handle_status = '1' 
                    AND claimed_by = $currentUserId";
        $validIds = $reportModel->query($checkSql);
        if ($validIds === false || count($validIds) <= 0) {
            error("您没有权限处理这些举报");
        }

        $validContentIds = array_column($validIds, 'report_id');
        $validIdsStr = "'" . implode("','", $validContentIds) . "'";
        $now = date('Y-m-d H:i:s');

        if($processType == 'confirm'){
            // 确认举报有效
            // 执行处理（更新状态为已处理）
            $updateSql = "UPDATE au_report_info 
                        SET handle_status = 2,
                            remark = CONCAT('违规类型：$violationType; 备注：$remark'),
                            updated_at = '$now'
                        WHERE report_id IN ($validIdsStr)";

            $affectedRows = $reportModel->execute($updateSql);
            if ($affectedRows <= 0) {
                error("处理举报失败");
            }

            // TODO: 这里需要调用对应类型内容的处理接口（如媒体/言论等的违规处理）

            success([
                'processedCount' => $affectedRows,
                'processedIds' => $validContentIds
            ], '批量处理完成');
        }else if($processType == 'reject'){
            // 驳回举报
            // 执行处理（更新状态为已处理）
            $updateSql = "UPDATE au_report_info 
                        SET handle_status = 3,
                            updated_at = '$now'
                        WHERE report_id IN ($validIdsStr)";

            $affectedRows = $reportModel->execute($updateSql);
            if ($affectedRows <= 0) {
                error("处理举报失败");
            }

            // TODO: 这里需要调用对应类型内容的处理接口（如媒体/言论等的违规处理）

            success([
                'processedCount' => $affectedRows,
                'processedIds' => $validContentIds
            ], '批量处理完成');
        }        
    }
    /**
     * 分页获取审核规则列表
     * @param {string} params.keyword - 搜索关键词（规则ID/名称/内容）
     * @param {string} params.applyType - 适用类型（媒体/言论/合集/全部，为空则查全部）
     * @param {number} params.status - 状态（1：启用，0：禁用，为空则查全部）
     * @param {number} params.sort - 排序方式（0：默认排序(创建时间降序)，1：创建时间降序，2：创建时间升序）
     * @param {number} params.page - 页码
     * @param {number} params.pageSize - 每页条数
     * @returns {Promise<Object>} 包含列表数据和分页信息的对象
     */
    function actionGetAuditRuleList() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $keyword = (string)arg("keyword", "");
        $applyType = (string)arg("applyType", "");
        $status = (int)arg("status", -1); // -1表示不筛选
        $sort = (int)arg("sort", 0);

        // 限制每页最大条数
        if ($pagesize > 10) {
            $pagesize = 10;
        }

        // 构建查询条件
        $where = " 1=1 ";
        if ($keyword !== "") {
            $keyword = addslashes($keyword);
            $where .= " and (rule_id like '%$keyword%' or name like '%$keyword%' or content like '%$keyword%')";
        }
        if ($applyType !== "") {
            $applyType = addslashes($applyType);
            $where .= " and apply_type = '$applyType'";
        }
        if ($status !== -1) {
            $where .= " and status = $status";
        }

        // 构建排序条件
        $sortSql = "created_at desc"; // 默认排序
        if ($sort == 1) {
            $sortSql = "created_at desc";
        } elseif ($sort == 2) {
            $sortSql = "created_at asc";
        }

        // 计算分页起始位置
        $start = ($pagenum - 1) * $pagesize;

        // 构建查询SQL
        $sql = "select * from au_audit_rule where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_audit_rule where $where";

        // 执行查询
        $auditRuleModel = new Rule(); 
        $ruleList = $auditRuleModel->query($sql);
        $totalData = $auditRuleModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;

        // 补充创建人名称
        $Auitor = new Auditor();
        $newList = [];
        foreach ($ruleList as $item) {
            $creator = $Auitor->find(["id" => $item["created_by"]]);
            $item["created_by_name"] = $creator ? $creator["real_name"] : "--";
            $newList[] = $item;
        }

        // 返回结果
        success([
            "list" => $newList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }
    /**
     * 获取单个审核规则详情
     * @param {string} params.ruleId - 规则业务ID（如"RUL-7890"）
     * @returns {Promise<Object>} 规则详情对象
     */
    function actionGetAuditRuleDetail() {
        $ruleId = (string)arg("ruleId", "");
        if (empty($ruleId)) {
            error("规则ID不能为空");
        }

        $auditRuleModel = new Rule();
        $rule = $auditRuleModel->find(["rule_id" => $ruleId]);
        if (!$rule) {
            error("规则不存在");
        }

        // 补充创建人名称
        $Auitor = new Auditor();
        $creator = $Auitor->find(["id" => $rule["created_by"]]);
        $rule["created_by_name"] = $creator ? $creator["real_name"] : "--";

        success($rule);
    }

    /**
     * 创建审核规则
     * @param {string} params.name - 规则名称
     * @param {string} params.content - 规则内容描述
     * @param {string} params.applyType - 适用类型（媒体/言论/合集/全部）
     * @param {number} params.status - 状态（1：启用，0：禁用，默认1）
     * @returns {Promise<Object>} 包含创建结果的对象
     */
    function actionCreateAuditRule() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 参数验证
        if (empty($params['name'])) {
            error("规则名称不能为空");
        }
        if (empty($params['content'])) {
            error("规则内容不能为空");
        }
        $applyTypes = ['媒体', '言论', '合集', '全部'];
        if (!in_array($params['apply_type'], $applyTypes)) {
            error("适用类型必须是：媒体/言论/合集/全部");
        }
        $status = isset($params['status']) ? (int)$params['status'] : 1;
        if (!in_array($status, [0, 1])) {
            error("状态必须是0（禁用）或1（启用）");
        }

        // 获取当前登录用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error("请先登录");
        }

        // 生成规则业务ID（RUL-时间戳后8位）
        $ruleId = $params["rule_id"] ?? 'RUL-' . substr(time(), -8) . rand(100, 999);

        // 执行插入
        $auditRuleModel = new Rule();
        $now = date('Y-m-d H:i:s');
        $insertSql = "insert into au_audit_rule (
            rule_id, name, content, apply_type, status, 
            created_by, created_at, updated_at
        ) values (
            '$ruleId', 
            '" . addslashes($params['name']) . "', 
            '" . addslashes($params['content']) . "', 
            '" . addslashes($params['apply_type']) . "', 
            $status, 
            $currentUserId, 
            '$now', 
            '$now'
        )";

        $result = $auditRuleModel->execute($insertSql);
        if (!$result) {
            error("创建规则失败");
        }

        success([
            'ruleId' => $ruleId,
            'name' => $params['name']
        ], "规则创建成功");
    }

    /**
     * 更新审核规则
     * @param {string} params.ruleId - 规则业务ID
     * @param {string} params.name - 规则名称（可选）
     * @param {string} params.content - 规则内容（可选）
     * @param {string} params.applyType - 适用类型（可选）
     * @returns {Promise<Object>} 更新结果
     */
    function actionUpdateAuditRule() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        if (empty($params['rule_id'])) {
            error("规则ID不能为空");
        }
        $ruleId = addslashes($params['rule_id']);

        // 验证规则是否存在
        $auditRuleModel = new Rule();
        $rule = $auditRuleModel->find(["rule_id" => $ruleId]);
        if (!$rule) {
            error("规则不存在");
        }

        // 构建更新字段
        $updateFields = [];
        if (isset($params['name']) && $params['name'] !== "") {
            $updateFields[] = "name = '" . addslashes($params['name']) . "'";
        }
        if (isset($params['content']) && $params['content'] !== "") {
            $updateFields[] = "content = '" . addslashes($params['content']) . "'";
        }
        $applyTypes = ['媒体', '言论', '合集', '全部'];
        if (isset($params['apply_type']) && in_array($params['apply_type'], $applyTypes)) {
            $updateFields[] = "apply_type = '" . addslashes($params['apply_type']) . "'";
        }
        if (empty($updateFields)) {
            error("没有需要更新的字段");
        }

        // 添加更新时间
        $now = date('Y-m-d H:i:s');
        $updateFields[] = "updated_at = '$now'";

        // 执行更新
        $updateSql = "update au_audit_rule set " . implode(', ', $updateFields) . " where rule_id = '$ruleId'";
        $result = $auditRuleModel->execute($updateSql);
        if (!$result) {
            error("更新规则失败");
        }

        success([
            'ruleId' => $ruleId
        ], "规则更新成功");
    }

    /**
     * 启用/禁用审核规则
     * @param {string} params.ruleId - 规则业务ID
     * @param {number} params.status - 状态（1：启用，0：禁用）
     * @returns {Promise<Object>} 操作结果
     */
    function actionChangeAuditRuleStatus() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        if (empty($params['ruleId'])) {
            error("规则ID不能为空");
        }
        if (!isset($params['status']) || !in_array($params['status'], [0, 1])) {
            error("状态必须是0（禁用）或1（启用）");
        }

        $ruleId = addslashes($params['ruleId']);
        $status = (int)$params['status'];

        // 验证规则存在
        $auditRuleModel = new Rule();
        $rule = $auditRuleModel->find(["rule_id" => $ruleId]);
        if (!$rule) {
            error("规则不存在");
        }

        // 执行状态更新
        $now = date('Y-m-d H:i:s');
        $updateSql = "update au_audit_rule set status = $status, updated_at = '$now' where rule_id = '$ruleId'";
        $result = $auditRuleModel->execute($updateSql);
        if (!$result) {
            error("状态更新失败");
        }

        success([
            'ruleId' => $ruleId,
            'status' => $status
        ], $status == 1 ? "规则已启用" : "规则已禁用");
    }

    /**
     * 删除审核规则
     * @param {string} params.ruleId - 规则业务ID
     * @returns {Promise<Object>} 操作结果
     */
    function actionDeleteRule(){
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        if (empty($params['ruleId'])) {
            error("规则ID不能为空");
        }
        $ruleId = addslashes($params['ruleId']);
        // 验证规则存在
        $auditRuleModel = new Rule();
        $rule = $auditRuleModel->find(["rule_id" => $ruleId]);
        if (!$rule) {
            error("规则不存在");
        }
        // 执行删除
        $deleteSql = "delete from au_audit_rule where rule_id = '$ruleId'";
        $result = $auditRuleModel->execute($deleteSql);
        if (!$result) {
            error("删除规则失败");
        }
        success([
            'ruleId' => $ruleId
        ], "规则删除成功");
    }

    /**
     * 获取敏感词列表（分页）
     * @param {number} params.page - 页码，默认1
     * @param {number} params.pageSize - 每页条数，默认10，最大20
     * @param {number} params.wordType - 敏感类型（1-色情低俗；2-暴力恐怖；3-政治敏感；4-辱骂攻击；5-广告营销；6-其他）
     * @param {number} params.level - 敏感级别（1-低；2-中；3-高）
     * @param {number} params.status - 状态（1-启用；0-禁用）
     * @param {string} params.keyword - 搜索关键词（匹配敏感词内容或别名）
     * @param {string} params.businessScope - 适用业务范围
     * @param {number} params.sort - 排序方式（0-默认排序；1-创建时间降序；2-创建时间升序）
     * @returns {Promise<Object>} 包含列表数据和分页信息的对象
     */
    function actionGetSensitiveWordList() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $wordType = (int)arg("wordType", 0);
        $level = (int)arg("level", 0);
        $status = (int)arg("status", -1); // -1表示不筛选
        $keyword = (string)arg("keyword", "");
        $businessScope = (string)arg("businessScope", "");
        $sort = (int)arg("sort", 0);

        // 限制每页最大条数
        if ($pagesize > 20) {
            $pagesize = 20;
        }

        // 构建查询条件（排除已删除）
        $where = " is_deleted = 0 ";
        if ($wordType != 0) {
            $where .= " and word_type = $wordType";
        }
        if ($level != 0) {
            $where .= " and level = $level";
        }
        if ($status != -1) {
            $where .= " and status = $status";
        }
        if ($keyword != "") {
            $keyword = addslashes($keyword);
            $where .= " and (word like '%$keyword%' or word_alias like '%$keyword%')";
        }
        if ($businessScope != "") {
            $businessScope = addslashes($businessScope);
            $where .= " and business_scope like '%$businessScope%'";
        }

        // 构建排序条件
        $sortSql = "id desc";
        if ($sort == 1) {
            $sortSql = "created_at desc";
        }
        if ($sort == 2) {
            $sortSql = "created_at asc";
        }

        // 计算分页
        $start = ($pagenum - 1) * $pagesize;

        // 执行查询
        $sensitiveWordModel = new SensitiveWords(); // 假设存在对应模型
        $sql = "select * from au_sensitive_word where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_sensitive_word where $where";
        
        $wordList = $sensitiveWordModel->query($sql);
        $totalData = $sensitiveWordModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;

        success([
            "list" => $wordList,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }

    /**
     * 获取敏感词详情
     * @param {number} params.id - 敏感词ID
     * @returns {Promise<Object>} 敏感词详情对象
     */
    function actionGetSensitiveWordDetail() {
        $id = (int)arg("id", 0);
        if ($id <= 0) {
            error("无效的敏感词ID");
        }

        $sensitiveWordModel = new SensitiveWords();
        $wordInfo = $sensitiveWordModel->find([
            "id" => $id,
            "is_deleted" => 0
        ]);

        if (!$wordInfo) {
            error("敏感词不存在或已删除");
        }

        success($wordInfo);
    }

    /**
     * 新增敏感词
     * @param {string} params.word - 敏感词内容（必填，唯一）
     * @param {string} params.word_alias - 敏感词别名（逗号分隔）
     * @param {number} params.word_type - 敏感类型（1-6，必填）
     * @param {number} params.level - 敏感级别（1-3，默认2）
     * @param {number} params.match_mode - 匹配模式（1-精确；2-模糊，默认1）
     * @param {string} params.replace_str - 替换字符串（默认*）
     * @param {number} params.status - 状态（1-启用；0-禁用，默认1）
     * @param {string} params.business_scope - 适用业务范围（逗号分隔）
     * @param {string} params.remark - 备注说明
     * @returns {Promise<Object>} 新增结果
     */
    function actionAddSensitiveWord() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证必填参数
        if (empty($params['word'])) {
            error("敏感词内容不能为空");
        }
        if (!isset($params['word_type']) || !in_array($params['word_type'], [1,2,3,4,5,6])) {
            error("请指定有效的敏感类型（1-6）");
        }

        // 处理参数
        $word = trim(addslashes($params['word']));
        $wordAlias = trim(addslashes($params['word_alias'] ?? ''));
        $wordType = (int)$params['word_type'];
        $level = in_array($params['level'] ?? 2, [1,2,3]) ? (int)$params['level'] : 2;
        $matchMode = in_array($params['match_mode'] ?? 1, [1,2]) ? (int)$params['match_mode'] : 1;
        $replaceStr = trim(addslashes($params['replace_str'] ?? '*'));
        $status = in_array($params['status'] ?? 1, [0,1]) ? (int)$params['status'] : 1;
        $businessScope = trim(addslashes($params['business_scope'] ?? ''));
        $remark = trim(addslashes($params['remark'] ?? ''));

        // 检查敏感词是否已存在
        $sensitiveWordModel = new SensitiveWords();
        $exists = $sensitiveWordModel->find([
            "word" => $word
        ]);
        if ($exists) {
            error("该敏感词已存在");
        }

        // 获取当前用户
        $currentUserId = $this->getLoginUserId();
        if (empty($currentUserId)) {
            error("请先登录");
        }

        // 执行新增
        $now = date('Y-m-d H:i:s');
        $insertData = [
            'word' => $word,
            'word_alias' => $wordAlias,
            'word_type' => $wordType,
            'level' => $level,
            'match_mode' => $matchMode,
            'replace_str' => $replaceStr,
            'status' => $status,
            'business_scope' => $businessScope,
            'remark' => $remark,
            'created_by' => $currentUserId,
            'updated_by' => $currentUserId,
            'created_at' => $now,
            'updated_at' => $now,
            'is_deleted' => 0
        ];

        $id = $sensitiveWordModel->create($insertData); // 假设模型有insert方法
        if (!$id) {
            error("新增敏感词失败");
        }

        success([
            'id' => $id,
            'word' => $word
        ], "敏感词新增成功");
    }

    /**
     * 编辑敏感词
     * @param {number} params.id - 敏感词ID（必填）
     * @param {string} params.word - 敏感词内容（唯一）
     * @param {string} params.word_alias - 敏感词别名（逗号分隔）
     * @param {number} params.word_type - 敏感类型（1-6）
     * @param {number} params.level - 敏感级别（1-3）
     * @param {number} params.match_mode - 匹配模式（1-精确；2-模糊）
     * @param {string} params.replace_str - 替换字符串
     * @param {number} params.status - 状态（1-启用；0-禁用）
     * @param {string} params.business_scope - 适用业务范围
     * @param {string} params.remark - 备注说明
     * @returns {Promise<Object>} 编辑结果
     */
    function actionEditSensitiveWord() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        // 验证必填参数
        if (empty($params['id']) || $params['id'] <= 0) {
            error("无效的敏感词ID");
        }
        if (empty($params['word'])) {
            error("敏感词内容不能为空");
        }
        if (!isset($params['word_type']) || !in_array($params['word_type'], [1,2,3,4,5,6])) {
            error("请指定有效的敏感类型（1-6）");
        }

        $id = (int)$params['id'];
        $word = trim(addslashes($params['word']));
        $wordType = (int)$params['word_type'];

        // 检查敏感词是否存在
        $sensitiveWordModel = new SensitiveWords();
        $wordInfo = $sensitiveWordModel->find([
            "id" => $id,
            "is_deleted" => 0
        ]);
        if (!$wordInfo) {
            error("敏感词不存在或已删除");
        }

        // 检查敏感词是否重复
        if ($word != $wordInfo['word']) {
            $exists = $sensitiveWordModel->find([
                "word" => $word
            ]);
            if ($exists) {
                error("该敏感词已存在");
            }
        }

        // 检查敏感词是否重复（排除当前ID）
        if ($word != $wordInfo['word']) {
            $exists = $sensitiveWordModel->find([
                "word" => $word,
                "is_deleted" => 0,
                "id" => $id
            ]);
            if ($exists) {
                error("该敏感词已存在");
            }
        }

        // 处理参数
        $updateData = [
            'word' => $word,
            'word_type' => $wordType,
            'word_alias' => trim(addslashes($params['word_alias'] ?? '')),
            'level' => in_array($params['level'] ?? 2, [1,2,3]) ? (int)$params['level'] : 2,
            'match_mode' => in_array($params['match_mode'] ?? 1, [1,2]) ? (int)$params['match_mode'] : 1,
            'replace_str' => trim(addslashes($params['replace_str'] ?? '*')),
            'status' => in_array($params['status'] ?? 1, [0,1]) ? (int)$params['status'] : 1,
            'business_scope' => trim(addslashes($params['business_scope'] ?? '')),
            'remark' => trim(addslashes($params['remark'] ?? '')),
            'updated_by' => $this->getLoginUserId(),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        // 执行更新
        $affectedRows = $sensitiveWordModel->update(["id" => $id],$updateData); // 假设模型有update方法
        if ($affectedRows == false) {
            error("编辑敏感词失败");
        }

        success([
            'id' => $id
        ], "敏感词编辑成功");
    }

    /**
     * 删除敏感词（逻辑删除）
     * @param {Array} params.ids - 敏感词ID数组（必填）
     * @returns {Promise<Object>} 删除结果
     */
    function actionDeleteSensitiveWord() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        if (empty($params['ids']) || !is_array($params['ids'])) {
            error("请传入有效的ID数组");
        }

        $ids = array_map(function($id) {
            return (int)$id;
        }, $params['ids']);
        $ids = array_filter($ids, function($id) {
            return $id > 0;
        });

        if (empty($ids)) {
            error("ID数组不能为空");
        }

        $sensitiveWordModel = new SensitiveWords();
        $idsStr = implode(',', $ids);
        
        // 检查是否存在有效记录
        $checkSql = "select count(*) as num from au_sensitive_word where id in ($idsStr) and is_deleted = 0";
        $checkData = $sensitiveWordModel->query($checkSql);
        if ($checkData[0]['num'] <= 0) {
            error("没有可删除的敏感词");
        }

        // 执行逻辑删除
        $updateSql = "update au_sensitive_word set 
                      is_deleted = 1,
                      updated_by = '{$this->getLoginUserId()}',
                      updated_at = '".date('Y-m-d H:i:s')."' 
                      where id in ($idsStr) and is_deleted = 0";
        
        $affectedRows = $sensitiveWordModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("删除敏感词失败");
        }

        success([
            'deletedCount' => $affectedRows,
            'deletedIds' => $ids
        ], "敏感词删除成功");
    }

    /**
     * 切换敏感词状态（启用/禁用）
     * @param {number} params.id - 敏感词ID（必填）
     * @param {number} params.status - 目标状态（1-启用；0-禁用，必填）
     * @returns {Promise<Object>} 操作结果
     */
    function actionToggleSensitiveWordStatus() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        if (empty($params['id']) || $params['id'] <= 0) {
            error("无效的敏感词ID");
        }
        if (!isset($params['status']) || !in_array($params['status'], [0,1])) {
            error("请指定有效的目标状态（0-禁用；1-启用）");
        }

        $id = (int)$params['id'];
        $status = (int)$params['status'];

        $sensitiveWordModel = new SensitiveWords();
        $wordInfo = $sensitiveWordModel->find([
            "id" => $id,
            "is_deleted" => 0
        ]);
        if (!$wordInfo) {
            error("敏感词不存在或已删除");
        }

        // 状态未变更则直接返回
        if ($wordInfo['status'] == $status) {
            success([
                'id' => $id,
                'status' => $status
            ], "敏感词状态已是" . ($status ? "启用" : "禁用"));
        }

        // 执行状态更新
        $updateSql = "update au_sensitive_word set 
                      status = $status,
                      updated_by = '{$this->getLoginUserId()}',
                      updated_at = '".date('Y-m-d H:i:s')."' 
                      where id = $id and is_deleted = 0";
        
        $affectedRows = $sensitiveWordModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("状态切换失败");
        }

        success([
            'id' => $id,
            'status' => $status
        ], "敏感词已" . ($status ? "启用" : "禁用"));
    }

    /**
     * 批量切换敏感词状态（启用/禁用）
     * @param {Array} params.ids - 敏感词ID数组（必填）
     * @param {number} params.status - 目标状态（1-启用；0-禁用，必填）
     * @returns {Promise<Object>} 操作结果
     */
    function actionBatchToggleSensitiveWordStatus() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);

        if (empty($params['ids']) || !is_array($params['ids'])) {
            error("请传入有效的ID数组");
        }
        if (!isset($params['status']) || !in_array($params['status'], [0,1])) {
            error("请指定有效的目标状态（0-禁用；1-启用）");
        }
        $ids = array_map(function($id) {
            return (int)$id;
        }, $params['ids']);
        $ids = array_filter($ids, function($id) {
            return $id > 0;
        });
        if (empty($ids)) {
            error("ID数组不能为空");
        }
        $idsStr = implode(',', $ids);
        $status = (int)$params['status'];
        $sensitiveWordModel = new SensitiveWords();
        $checkSql = "select count(*) as num from au_sensitive_word where id in ($idsStr) and is_deleted = 0";
        $checkData = $sensitiveWordModel->query($checkSql);
        if ($checkData[0]['num'] <= 0) {
            error("没有可切换状态的敏感词");
        }
        $updateSql = "update au_sensitive_word set 
                      status = $status,
                      updated_by = '{$this->getLoginUserId()}',
                      updated_at = '".date('Y-m-d H:i:s')."' 
                      where id in ($idsStr) and is_deleted = 0";
        $affectedRows = $sensitiveWordModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error("状态切换失败");
        }
        success([
            'ids' => $ids,
            'status' => $status
        ], "敏感词状态已切换");


    }

    /**
     * 新增审核流程
     * @param {string} params.name - 流程名称（必填）
     * @param {string} params.steps - 流程步骤（JSON格式，必填，如[{"step":1,"name":"AI预审"},{"step":2,"name":"人工审核"}]）
     * @param {string} params.apply_type - 适用类型（必填，如"媒体/言论/合集"）
     * @param {number} params.status - 状态（可选，1：启用，0：禁用，默认1）
     * @returns {Promise<Object>} 包含新增流程信息的对象
     * @throws {Error} 当参数无效或插入失败时抛出异常
     */
    function actionAddAuditWorkflow() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        // 参数验证
        if (empty($params['name'])) {
            error('流程名称不能为空');
        }
        if (empty($params['steps'])) {
            error('流程步骤不能为空');
        }
        // 验证JSON格式
        $stepsJson = json_decode($params['steps'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error('流程步骤格式错误，必须为有效的JSON');
        }
        if (empty($params['apply_type'])) {
            error('适用类型不能为空');
        }
        $status = isset($params['status']) ? (int)$params['status'] : 1;
        if (!in_array($status, [0, 1])) {
            error('状态必须为0（禁用）或1（启用）');
        }
        
        // 生成业务ID（FLW-前缀+日期+随机数）
        $flowId = 'FLW-' . date('Ymd') . mt_rand(1000, 9999);
        
        // 实例化模型（假设存在AuditWorkflow模型）
        $workflowModel = new Workflow();
        
        // 插入数据
        $now = date('Y-m-d H:i:s');
        $insertSql = "INSERT INTO au_audit_workflow 
                    (flow_id, name, steps, apply_type, status, created_at, updated_at) 
                    VALUES 
                    ('$flowId', '".addslashes($params['name'])."', '".addslashes($params['steps'])."', '".addslashes($params['apply_type'])."', $status, '$now', '$now')";
        
        $result = $workflowModel->execute($insertSql);
        if (!$result) {
            error('新增审核流程失败');
        }
        
        // 获取新增的流程信息
        $newWorkflow = $workflowModel->find(["flow_id" => $flowId]);
        success($newWorkflow, '审核流程新增成功');
    }

    /**
     * 获取审核流程列表
     * @param {string} params.apply_type - 适用类型筛选（可选）
     * @param {number} params.status - 状态筛选（可选，0：禁用，1：启用）
     * @param {string} params.keyword - 关键词搜索（名称，可选）
     * @param {number} params.page - 页码（默认1）
     * @param {number} params.pageSize - 每页条数（默认10，最大10）
     * @returns {Promise<Object>} 包含列表数据和分页信息的对象
     */
    function actionGetAuditWorkflowList() {
        // 接收参数
        $pagenum = (int)arg("page", 1);
        $pagesize = (int)arg("pageSize", 10);
        $applyType = (string)arg("applyType", "");
        $status = (int)arg("status", -1); // -1表示不筛选
        
        // 限制每页最大条数
        if ($pagesize > 10) {
            $pagesize = 10;
        }
        
        // 构建查询条件
        $where = "1=1";
        if ($applyType !== "") {
            $where .= " and apply_type = '".addslashes($applyType)."'";
        }
        if ($status !== -1) {
            $where .= " and status = $status";
        }
        
        // 排序条件（默认按创建时间降序）
        $sortSql = "created_at desc";
        
        // 分页计算
        $start = ($pagenum - 1) * $pagesize;
        
        // 执行查询
        $workflowModel = new Workflow();
        $sql = "select * from au_audit_workflow where $where order by $sortSql limit $start, $pagesize";
        $sqlCount = "select count(*) as total from au_audit_workflow where $where";
        
        $list = $workflowModel->query($sql);
        $totalData = $workflowModel->query($sqlCount);
        $total = $totalData[0]["total"] ?? 0;
        
        // 处理步骤JSON为数组
        foreach ($list as &$item) {
            $item['steps'] = json_decode($item['steps'], true);
        }
        
        success([
            "list" => $list,
            "total" => $total,
            "pagesize" => $pagesize,
            "page" => $pagenum,
        ]);
    }

    /**
     * 获取审核流程详情
     * @param {string} params.flow_id - 流程业务ID（必填，如"FLW-2468"）
     * @returns {Promise<Object>} 流程详细信息
     * @throws {Error} 当流程不存在时抛出异常
     */
    function actionGetAuditWorkflowDetail() {
        $flowId = (string)arg("flow_id", "");
        if (empty($flowId)) {
            error('flow_id不能为空');
        }
        
        $workflowModel = new Workflow();
        $workflow = $workflowModel->find(["flow_id" => $flowId]);
        if (!$workflow) {
            error('审核流程不存在');
        }
        
        // 解析steps为数组
        $workflow['steps'] = json_decode($workflow['steps'], true);
        
        success($workflow);
    }

    /**
     * 更新审核流程
     * @param {string} params.flow_id - 流程业务ID（必填）
     * @param {string} params.name - 流程名称（可选）
     * @param {string} params.steps - 流程步骤（JSON格式，可选）
     * @param {string} params.apply_type - 适用类型（可选）
     * @param {number} params.status - 状态（可选，0：禁用，1：启用）
     * @returns {Promise<Object>} 更新结果
     * @throws {Error} 当参数无效或更新失败时抛出异常
     */
    function actionUpdateAuditWorkflow() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        if (empty($params['flow_id'])) {
            error('flow_id不能为空');
        }
        $flowId = $params['flow_id'];
        
        // 验证流程是否存在
        $workflowModel = new Workflow();
        $exist = $workflowModel->find(["flow_id" => $flowId]);
        if (!$exist) {
            error('审核流程不存在');
        }
        
        // 构建更新字段
        $updateFields = [];
        if (isset($params['name']) && $params['name'] !== "") {
            $updateFields[] = "name = '".addslashes($params['name'])."'";
        }
        if (isset($params['steps']) && $params['steps'] !== "") {
            // 验证JSON格式
            $stepsJson = json_decode($params['steps'], true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                error('流程步骤格式错误，必须为有效的JSON');
            }
            $updateFields[] = "steps = '".addslashes($params['steps'])."'";
        }
        if (isset($params['apply_type']) && $params['apply_type'] !== "") {
            $updateFields[] = "apply_type = '".addslashes($params['apply_type'])."'";
        }
        if (isset($params['status'])) {
            $status = (int)$params['status'];
            if (!in_array($status, [0, 1])) {
                error('状态必须为0（禁用）或1（启用）');
            }
            $updateFields[] = "status = $status";
        }
        
        if (empty($updateFields)) {
            error('没有需要更新的字段');
        }
        
        // 执行更新
        $now = date('Y-m-d H:i:s');
        $updateFields[] = "updated_at = '$now'";
        $updateSql = "UPDATE au_audit_workflow SET ".implode(', ', $updateFields)." WHERE flow_id = '$flowId'";
        
        $affectedRows = $workflowModel->execute($updateSql);
        if ($affectedRows <= 0) {
            error('更新审核流程失败');
        }
        
        // 返回更新后的信息
        $updatedWorkflow = $workflowModel->find(["flow_id" => $flowId]);
        $updatedWorkflow['steps'] = json_decode($updatedWorkflow['steps'], true);
        success($updatedWorkflow, '审核流程更新成功');
    }

    /**
     * 禁用/启用审核流程（状态切换）
     * @param {string} params.flow_id - 流程业务ID（必填）
     * @param {number} params.status - 目标状态（0：禁用，1：启用，必填）
     * @returns {Promise<Object>} 操作结果
     * @throws {Error} 当参数无效或操作失败时抛出异常
     */
    function actionToggleAuditWorkflowStatus() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        if (empty($params['flow_id'])) {
            error('flow_id不能为空');
        }
        if (!isset($params['status']) || !in_array($params['status'], [0, 1])) {
            error('状态必须为0（禁用）或1（启用）');
        }
        
        $flowId = $params['flow_id'];
        $status = (int)$params['status'];
        
        $workflowModel = new Workflow();
        $exist = $workflowModel->find(["flow_id" => $flowId]);
        if (!$exist) {
            error('审核流程不存在');
        }
        
        $now = date('Y-m-d H:i:s');
        $updateSql = "UPDATE au_audit_workflow SET status = $status, updated_at = '$now' WHERE flow_id = '$flowId'";
        $affectedRows = $workflowModel->execute($updateSql);
        
        if ($affectedRows <= 0) {
            error('状态更新失败');
        }
        
        success([
            'flow_id' => $flowId,
            'status' => $status
        ], $status == 1 ? '审核流程已启用' : '审核流程已禁用');
    }

    /**
     * 删除审核流程
     * @param {string} params.flow_id - 流程业务ID（必填）
     * @returns {Promise<Object>} 操作结果
     * @throws {Error} 当参数无效或删除失败时抛出异常
     */
    function actionDeleteAuditWorkflow() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true);
        
        if (empty($params['flow_id'])) {
            error('flow_id不能为空');
        }
        $flowId = $params['flow_id'];
        
        $workflowModel = new Workflow();
        $exist = $workflowModel->find(["flow_id" => $flowId]);
        if (!$exist) {
            error('审核流程不存在');
        }
        // 检查是否有正在使用的实例
        $instanceModel = new Workflow();
        $instance = $instanceModel->find(["flow_id" => $flowId,"status"=>1]);
        if ($instance) {
            error('当前审核流程有正在使用的实例，不能删除');
        }
        // 删除
        $affectedRows = $workflowModel->delete(["flow_id" => $flowId]);
        if ($affectedRows <= 0) {
            error('删除审核流程失败');
        }
        success([
            'flow_id' => $flowId
        ], '审核流程删除成功');
    }

    /**
     * 获取审核员列表（带筛选和分页）
     * @param {number} params.page - 页码（默认1）
     * @param {number} params.pagesize - 每页条数（默认10）
     * @param {string} params.keyword - 用户名/姓名搜索关键词
     * @param {number} params.role - 角色ID筛选
     * @param {number} params.status - 状态筛选（1启用，0禁用）
     * @param {string} params.mobile - 手机号筛选
     * @returns {Promise<Object>} 列表数据及分页信息
     */
    function actionGetAuditorList() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true) ?? [];

        // 分页参数
        $page = max(1, (int)($params['page'] ?? 1));
        $pagesize = (int)($params['pagesize'] ?? 10);
        $start = ($page - 1) * $pagesize;

        // 筛选条件
        $where = "1=1";
        if (!empty($params['keyword'])) {
            $keyword = addslashes($params['keyword']);
            $where .= " AND (username LIKE '%$keyword%' OR real_name LIKE '%$keyword%')";
        }
        if (isset($params['role']) && $params['role'] !== '') {
            $where .= " AND role = " . (int)$params['role'];
        }
        if (isset($params['status']) && $params['status'] !== '') {
            $where .= " AND status = " . (int)$params['status'];
        }
        if (!empty($params['mobile'])) {
            $mobile = addslashes($params['mobile']);
            $where .= " AND mobile = '$mobile'";
        }

        // 查询总数
        $auditorModel = new Auditor();
        $totalSql = "SELECT COUNT(*) AS total FROM au_auditor WHERE $where";
        $totalData = $auditorModel->query($totalSql);
        $total = $totalData[0]['total'] ?? 0;

        // 查询列表
        $listSql = "SELECT * FROM au_auditor WHERE $where ORDER BY created_at DESC LIMIT $start, $pagesize";
        $list = $auditorModel->query($listSql);

        // 补充角色名称
        $roleModel = new Role();
        foreach ($list as &$item) {
            $role = $roleModel->find(['role_id' => $item['role']]);
            $item['role_name'] = $role ? $role['role_name'] : '';
        }

        success([
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'pagesize' => $pagesize
        ]);
    }

    /**
     * 添加审核员
     * @param {string} params.username - 登录用户名（必填）
     * @param {string} params.password - 密码（必填，至少8位，含字母和数字）
     * @param {string} params.real_name - 真实姓名（必填）
     * @param {number} params.role_id - 角色ID（必填）
     * @param {string} params.mobile - 手机号（可选）
     * @param {string} params.avatar - 头像URL（可选）
     * @returns {Promise<Object>} 操作结果
     */
    function actionAddAuditor() {
        // 参数验证
        if (empty(arg('username',""))) {
            error('用户名不能为空');
        }
        if (empty(arg('password',""))) {
            error('密码不能为空');
        }
        // 密码格式验证
        if (strlen(arg('password',"")) < 8 || !preg_match('/[a-zA-Z]/', arg('password',"")) || !preg_match('/[0-9]/', arg('password',""))) {
            error('密码长度至少8位，且必须包含字母和数字');
        }
        if (empty(arg('real_name',""))) {
            error('真实姓名不能为空');
        }
        if (empty(arg('role_id',""))) {
            error('请选择角色');
        }

        $avatar = arg('avatar',"");

        $auditorModel = new Auditor();
        // 验证用户名唯一性
        $exist = $auditorModel->find(['username' => arg('username',"")]);
        if ($exist) {
            error('用户名已存在');
        }

        // 密码加密（示例使用password_hash，实际可根据项目规范调整）
        $hashedPassword = password_hash(arg('password',""), PASSWORD_DEFAULT);

        // 插入审核员信息
        $now = date('Y-m-d H:i:s');
        $insertSql = "INSERT INTO au_auditor (
            username, password, real_name, role, mobile, avatar, created_at, updated_at
        ) VALUES (
            '" . addslashes(arg('username',"")) . "',
            '$hashedPassword',
            '" . addslashes(arg('real_name',"")) . "',
            " . (int)arg('role_id',"") . ",
            '" . addslashes(arg('mobile',"")) . "',
            '" . addslashes($avatar) . "',
            '$now',
            '$now'
        )";
        $userId = $auditorModel->query($insertSql);
        if ($userId == false) {
            error('添加审核员失败');
        }

        // 关联用户角色
        $userRoleModel = new UserRole();
        $userRoleModel->query("INSERT INTO au_user_roles (user_id, role_id, created_at) VALUES ($userId, " . (int)arg('role_id',"") . ", '$now')");

        success([
            'userId' => $userId,
            'username' => arg('username',"")
        ], '审核员添加成功');
    }

    /**
     * 删除审核员
     * @param {number} params.id - 审核员ID（必填）
     * @returns {Promise<Object>} 操作结果
     */
    function actionDeleteAuditor(){
        if (empty(arg('id',""))) {
            error('审核员ID不能为空');
        }
        $id = (int)arg('id',"");
        $auditorModel = new Auditor();
        $auditorModel->query("DELETE FROM au_auditor WHERE id = $id");
        success([], '审核员删除成功');
    }

    /**
     * 编辑审核员信息
     * @param {number} params.id - 审核员ID（必填）
     * @param {string} params.real_name - 真实姓名（可选）
     * @param {string} params.mobile - 手机号（可选）
     * @param {string} params.avatar - 头像URL（可选）
     * @param {number} params.status - 状态（1启用，0禁用，可选）
     * @param {number} params.role_id - 角色ID（可选）
     * @returns {Promise<Object>} 操作结果
     */
    function actionEditAuditor() {

        if (empty(arg('id',""))) {
            error('审核员ID不能为空');
        }
        $id = (int)arg('id',"");

        // 验证审核员是否存在
        $auditorModel = new Auditor();
        $auditor = $auditorModel->find(['id' => $id]);
        if (!$auditor) {
            error('审核员不存在');
        }

        // 构建更新字段
        $updateFields = [];
        if (!empty(arg('real_name',""))) {
            $updateFields[] = "real_name = '" . addslashes(arg('real_name',"")) . "'";
        }
        if (null !== arg('mobile',"")) {
            $updateFields[] = "mobile = '" . addslashes(arg('mobile',"")) . "'";
        }
        if (!empty(arg('avatar',""))) {
            $updateFields[] = "avatar = '" . addslashes(arg('avatar',"")) . "'";
        }
        if (null !== arg('status',"")) {
            $updateFields[] = "status = " . (int)arg('status',"");
        }
        if (empty($updateFields) && null !== arg('role_id', "")) {
            error('没有需要更新的字段');
        }

        // 更新审核员信息
        if (!empty($updateFields)) {
            $updateFields[] = "updated_at = '" . date('Y-m-d H:i:s') . "'";
            $updateSql = "UPDATE au_auditor SET " . implode(', ', $updateFields) . " WHERE id = $id";
            $auditorModel->query($updateSql);
        }

        // 更新角色（如果有）
        if (isset($params['role_id'])) {
            $roleId = (int)$params['role_id'];
            $userRoleModel = new UserRole();
            // 先删除旧关联
            $userRoleModel->delete(["user_id"=>$id]);
            // 添加新关联
            $userRoleModel->query("INSERT INTO au_user_roles (user_id, role_id, created_at) VALUES ($id, $roleId, '" . date('Y-m-d H:i:s') . "')");
            // 更新au_auditor表中的role字段
            $auditorModel->query("UPDATE au_auditor SET role = $roleId, updated_at = '" . date('Y-m-d H:i:s') . "' WHERE id = $id");
        }

        success([], '审核员信息更新成功');
    }

    /**
     * 启用/禁用审核员
     * @param {number} params.id - 审核员ID（必填）
     * @param {number} params.status - 状态（1启用，0禁用，必填）
     * @returns {Promise<Object>} 操作结果
     */
    function actionChangeAuditorStatus() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true) ?? [];

        if (empty($params['id'])) {
            error('审核员ID不能为空');
        }
        if (!isset($params['status']) || !in_array($params['status'], [0, 1])) {
            error('状态必须为0（禁用）或1（启用）');
        }

        $id = (int)$params['id'];
        $status = (int)$params['status'];

        $auditorModel = new Auditor();
        $auditor = $auditorModel->find(['id' => $id]);
        if (!$auditor) {
            error('审核员不存在');
        }

        $auditorModel->query("UPDATE au_auditor SET status = $status, updated_at = '" . date('Y-m-d H:i:s') . "' WHERE id = $id");
        success([], $status ? '审核员已启用' : '审核员已禁用');
    }

    /**
     * 获取审核员详情（含角色权限）
     * @param {number} params.id - 审核员ID（必填）
     * @returns {Promise<Object>} 审核员详情
     */
    function actionGetAuditorDetail() {
        $id = (int)arg('id', 0);
        if ($id <= 0) {
            error('审核员ID不能为空');
        }

        // 获取审核员基本信息
        $auditorModel = new Auditor();
        $auditor = $auditorModel->find(['id' => $id]);
        if (!$auditor) {
            error('审核员不存在');
        }

        // 获取角色信息
        $roleId = $auditor['role'];
        $roleModel = new Role();
        $role = $roleModel->find(['role_id' => $roleId]);
        $auditor['role_info'] = $role ?? [];

        // 获取权限列表
        $permModel = new Permissions();
        $permissions = $permModel->query("SELECT permission_id FROM au_role_permissions WHERE role_id = $roleId");
        $auditor['permission_ids'] = array_column($permissions, 'permission_id');

        success($auditor);
    }

    /**
     * 获取角色列表
     * @returns {Promise<Array>} 角色列表
     */
    function actionGetRoleList() {
        $roleModel = new Role();
        $roles = $roleModel->query("SELECT role_id, role_name, role_desc FROM au_roles WHERE is_active = 1 ORDER BY role_id ASC");
        success($roles);
    }

    /**
     * 分配审核员权限（通过角色）
     * @param {number} params.user_id - 审核员ID（必填）
     * @param {number} params.role_id - 角色ID（必填）
     * @returns {Promise<Object>} 操作结果
     */
    function actionAssignRole() {
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true) ?? [];

        if (empty($params['user_id']) || empty($params['role_id'])) {
            error('用户ID和角色ID不能为空');
        }
        $userId = (int)$params['user_id'];
        $roleId = (int)$params['role_id'];

        // 验证角色是否存在
        $roleModel = new Role();
        $role = $roleModel->find(['role_id' => $roleId, 'is_active' => 1]);
        if (!$role) {
            error('角色不存在或已禁用');
        }

        // 更新用户角色关联
        $userRoleModel = new UserRole();
        $userRoleModel->delete(["user_id"=>$userId]);
        $userRoleModel->query("INSERT INTO au_user_roles (user_id, role_id, created_at) VALUES ($userId, $roleId, '" . date('Y-m-d H:i:s') . "')");

        // 更新审核员表中的角色字段
        $auditorModel = new Auditor();
        $auditorModel->query("UPDATE au_auditor SET role = $roleId, updated_at = '" . date('Y-m-d H:i:s') . "' WHERE id = $userId");

        success([], '角色分配成功');
    }
    /**
     * 单文件上传
    */
    function putObjectByFile($file,$key,$Bucket="butket1apk"){
    	if(Utils::chk_chinese($file)){
    		$file = iconv('utf-8','gbk',$file);
    	}
    	$content = $file;
    	$total = Utils::getFileSize($file);
    	$args = array(
    		"Bucket"=>$Bucket,
    		"Key"=>$key,
    		"ACL"=>"public-read",
    		"ObjectMeta"=>array(
    			"Content-Length"=>$total
    			),
    		"Content"=>array(
    			"content"=>$content
    		),
    	);
        $client = new Ks3Client("AKLTRy8w6Sg5TsiKlqptxF4Few","OFtAroQ8SOaSgtlHM6DlVaKNcZ9Psa2O0l0Rpr8Oj6XqTOww9XStw+PhXOjihLi5Kw==","ks3-cn-beijing.ksyun.com");
    	return $client->putObjectByFile($args);
    }
    /**
     * 文件上传
     */
    function actionUploadfileForAmis(){
        $file = $_FILES['file'];
        if ($_FILES['file']['error'] == 0) {
            $file_path = $_SERVER["DOCUMENT_ROOT"].'/uploads/';//设置文件路径
            $file_name = $file['name'];//文件名称
            $info = pathinfo($file_name);
            $ext = $info['extension'];
            $newfilename = date('YmdHis').'.'.$ext;
            move_uploaded_file($_FILES["file"]["tmp_name"], $file_path . $newfilename);
            //文件分发到云端
            $result = $this->putObjectByFile($file_path.$newfilename,'uploads/'.$newfilename);
                if(isset($result['ETag']) && !empty($result['ETag'])){
                    echo json_encode(array(
                        "status"=>0,
                        "msg"=>"上传成功",
                        "data"=>array(
                            "value"=>'http://p4.renbenzhihui.com/uploads/'.$newfilename
                            )
                        ));
                    exit();
                }else{
                    $data['status'] = 400;
                    $data['msg'] = 'error code:' . $_FILES['file']['error'];
                    $data['file_path'] = '';
                    echo json_encode($data);
                }
        } else {
            $data['status'] = 400;
            $data['msg'] = 'error code:上传失败';
            $data['file_path'] = '';
            echo json_encode($data);
        }
    }

    /**
     * 获取权限列表
     */
    function actionGetPermission(){
        $pid = arg("pid",0);
        $permission = new Permission();
        $result = $permission->findAll(["parent_id"=>$pid]);
        success($result);
    }

    /**
     * 根据用户ID获取用户角色和权限列表
     */
    function actionGetUserPermission(){
        $userId = arg("user_id",0);
        // 验证用户ID
        if (empty($userId) || !is_numeric($userId)) {
            return ['error' => '无效的用户ID'];
            error("无效的用户ID");
        }

        $db = new Model();
        
        // 查询用户角色
        $roleSql = "
            SELECT r.role_id, r.role_name, r.role_desc 
            FROM au_roles r
            INNER JOIN au_user_roles ur ON r.role_id = ur.role_id
            WHERE ur.user_id = :user_id AND r.is_active = 1
        ";
        $roles = $db->query($roleSql,["user_id"=>$userId]);
        
        // 查询用户权限（包含parent_id=0和1）
        $permissionSql = "
            SELECT p.permission_id, p.permission_name, p.permission_key, 
                p.permission_desc, p.parent_id
            FROM au_permissions p
            INNER JOIN au_role_permissions rp ON p.permission_id = rp.permission_id
            INNER JOIN au_user_roles ur ON rp.role_id = ur.role_id
            WHERE ur.user_id = :user_id 
            AND p.parent_id IN (0, 1)  -- 只获取parent_id为0和1的权限
            GROUP BY p.permission_id  -- 去重
            ORDER BY p.parent_id, p.permission_id
        ";
        $permissions = $db->query($permissionSql,["user_id"=>$userId]);
        $hxPermission = [];
        $stPermission = [];
        foreach($permissions as $v){
            if($v['parent_id'] == 0){
                $hxPermission[] = $v['permission_id'];
            }else{
                $stPermission[] = $v['permission_id'];
            }
        }
        success([
            'user_id' => $userId,
            'role_id' => count($roles)>0?$roles[0]['role_id']:0,
            'hx_permission'=>implode(",",$hxPermission),
            'st_permission'=>implode(",",$stPermission),
        ]);
    }

    /**
     * 保存权限
     */
    function actionSavePermission(){
        $jsonInput = file_get_contents('php://input');
        $params = json_decode($jsonInput, true) ?? [];
        $roleId = $params['role_id'] ?? 0;
        $hxPermission = $params['hx_permission'] ?? "";
        $stPermission = $params['st_permission'] ?? "";
        $userId = $params['user_id'] ?? 0;


        if(empty($roleId) || empty($hxPermission) || empty($stPermission)){
            error("参数错误");
        }
        $db = new Model();
        $db->query("DELETE FROM au_role_permissions WHERE role_id = :role_id",["role_id"=>$roleId]);
        $hxPermission = explode(",",$hxPermission);
        $stPermission = explode(",",$stPermission);
        foreach($hxPermission as $v){
            $db->query("INSERT INTO au_role_permissions (role_id, permission_id) VALUES (:role_id, :permission_id)",[":role_id"=>$roleId,":permission_id"=>$v]);
        }
        foreach($stPermission as $v){
            $db->query("INSERT INTO au_role_permissions (role_id, permission_id) VALUES (:role_id, :permission_id)",[":role_id"=>$roleId,":permission_id"=>$v]);
        }
        // 更新用户的角色信息
        $db->query("UPDATE au_user_roles SET role_id = :role_id WHERE user_id = :user_id",[":role_id"=>$roleId,":user_id"=>$userId]);
        success([],'保存成功');
    }

    /**
     * 获取平台内所有待审任务数量总和
     * 待审任务包括：
     * - 媒体内容（待审核/再次审核）
     * - 内容合集（待审核/再次审核）
     * - 言论内容（待审核/再次审核）
     * - 认证申请（待审核）
     * @returns {Promise<Object>} 包含各类型待审数量及总数量的对象
     */
    function actionGetTotalPendingTasks() {
        // 定义各表待审状态条件
        $conditions = [
            'media' => [
                'table' => 'au_media_content',
                'where' => "audit_status IN (1, 4)" // 1:待审核 4:再次审核
            ],
            'collection' => [
                'table' => 'au_content_collection',
                'where' => "audit_status IN (1, 4)" // 1:待审核 4:再次审核
            ],
            'comment' => [
                'table' => 'au_comment_content',
                'where' => "audit_status IN (1, 4) AND is_deleted = 0" // 排除已删除的
            ],
            'certification' => [
                'table' => 'au_certification_apply',
                'where' => "audit_status = 1 AND is_deleted = 0" // 1:待审核 且有效
            ]
        ];
        
        $total = 0;
        $result = [];
        
        // 遍历查询各类型待审数量
        foreach ($conditions as $type => $conf) {
            $sql = "SELECT COUNT(*) as num FROM {$conf['table']} WHERE {$conf['where']}";
            
            // 使用通用模型查询（假设存在基础模型类）
            $model = new Model(); // 假设存在基础模型
            $data = $model->query($sql);
            $count = (int)($data[0]['num'] ?? 0);
            
            $result[$type] = $count;
            $total += $count;
        }
        
        $result['total'] = $total;
        
        success($result);
    }

    

    
}